示例#1
0
        public void FillPolygon_ImageBrush_Rect <TPixel>(TestImageProvider <TPixel> provider, string brushImageName)
            where TPixel : unmanaged, IPixel <TPixel>
        {
            PointF[] simplePath =
            {
                new Vector2(10, 10), new Vector2(200, 50), new Vector2(50, 200)
            };

            using (var brushImage = Image.Load <TPixel>(TestFile.Create(brushImageName).Bytes))
            {
                float top    = brushImage.Height / 4;
                float left   = brushImage.Width / 4;
                float height = top * 2;
                float width  = left * 2;

                var brush = new ImageBrush(brushImage, new RectangleF(left, top, width, height));

                provider.RunValidatingProcessorTest(
                    c => c.FillPolygon(brush, simplePath),
                    System.IO.Path.GetFileNameWithoutExtension(brushImageName) + "_rect",
                    appendSourceFileOrDescription: false);
            }
        }
        public void IgnoreMetadata_ControlsWhetherMetadataIsParsed(bool ignoreMetadata)
        {
            var decoder = new JpegDecoder {
                IgnoreMetadata = ignoreMetadata
            };

            // Snake.jpg has both Exif and ICC profiles defined:
            var testFile = TestFile.Create(TestImages.Jpeg.Baseline.Snake);

            using (Image <Rgba32> image = testFile.CreateRgba32Image(decoder))
            {
                if (ignoreMetadata)
                {
                    Assert.Null(image.Metadata.ExifProfile);
                    Assert.Null(image.Metadata.IccProfile);
                }
                else
                {
                    Assert.NotNull(image.Metadata.ExifProfile);
                    Assert.NotNull(image.Metadata.IccProfile);
                }
            }
        }
        public void Encode_IgnoreMetadataIsTrue_CommentsAreNotWritten()
        {
            var options = new GifEncoder()
            {
                IgnoreMetadata = true
            };

            var testFile = TestFile.Create(TestImages.Gif.Rings);

            using (Image <Rgba32> input = testFile.CreateImage())
            {
                using (var memStream = new MemoryStream())
                {
                    input.SaveAsGif(memStream, options);

                    memStream.Position = 0;
                    using (var output = Image.Load <Rgba32>(memStream))
                    {
                        Assert.Equal(0, output.MetaData.Properties.Count);
                    }
                }
            }
        }
示例#4
0
        public void Encode_IgnoreMetadataIsFalse_ExifProfileIsWritten()
        {
            JpegEncoder options = new JpegEncoder()
            {
                IgnoreMetadata = false
            };

            TestFile testFile = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan);

            using (Image <Rgba32> input = testFile.CreateImage())
            {
                using (MemoryStream memStream = new MemoryStream())
                {
                    input.Save(memStream, options);

                    memStream.Position = 0;
                    using (Image <Rgba32> output = Image.Load <Rgba32>(memStream))
                    {
                        Assert.NotNull(output.MetaData.ExifProfile);
                    }
                }
            }
        }
示例#5
0
        public void Encode_PreserveRatio(string imagePath, int xResolution, int yResolution, PixelResolutionUnit resolutionUnit)
        {
            var options = new PngEncoder();

            var testFile = TestFile.Create(imagePath);

            using (Image <Rgba32> input = testFile.CreateImage())
            {
                using (var memStream = new MemoryStream())
                {
                    input.Save(memStream, options);

                    memStream.Position = 0;
                    using (var output = Image.Load <Rgba32>(memStream))
                    {
                        ImageMetadata meta = output.Metadata;
                        Assert.Equal(xResolution, meta.HorizontalResolution);
                        Assert.Equal(yResolution, meta.VerticalResolution);
                        Assert.Equal(resolutionUnit, meta.ResolutionUnits);
                    }
                }
            }
        }
示例#6
0
        public void TgaEncoder_WithCompression_PreserveBitsPerPixel(string imagePath, TgaBitsPerPixel bmpBitsPerPixel)
        {
            var options = new TgaEncoder()
            {
                Compression = TgaCompression.RunLength
            };

            TestFile testFile = TestFile.Create(imagePath);

            using (Image <Rgba32> input = testFile.CreateRgba32Image())
            {
                using (var memStream = new MemoryStream())
                {
                    input.Save(memStream, options);
                    memStream.Position = 0;
                    using (var output = Image.Load <Rgba32>(memStream))
                    {
                        TgaMetadata meta = output.Metadata.GetTgaMetadata();
                        Assert.Equal(bmpBitsPerPixel, meta.BitsPerPixel);
                    }
                }
            }
        }
示例#7
0
        public void LoadResizeSave(string imagePath)
        {
            var configuration = Configuration.CreateDefaultInstance();

            configuration.MaxDegreeOfParallelism = 1;

            byte[] imageBytes = TestFile.Create(imagePath).Bytes;

            using (var ms = new MemoryStream())
            {
                this.Measure(
                    30,
                    () =>
                {
                    using (var image = Image.Load(configuration, imageBytes))
                    {
                        image.Mutate(x => x.Resize(image.Size() / 4));
                        image.SaveAsJpeg(ms);
                    }

                    ms.Seek(0, SeekOrigin.Begin);
                });
            }
        }
        private Image <Rgba32> Transform(int width, int height, ImageResizeMode mode)
        {
            var transformer = new ImageSharpImageTransformer();

            var imageStyle = new ImageStyle("test")
            {
                ResizeOptions = new ImageResizeOptions
                {
                    Width  = width,
                    Height = height,
                    Mode   = mode
                }
            };

            var configuration = Configuration.Default;

            var bytes = TestFile.Create(TestImages.Jpeg.Lake).Bytes;

            var image = SixLabors.ImageSharp.Image.Load(configuration, bytes);

            transformer.Transform(image, imageStyle);

            return(image);
        }
        protected void RunTest(string name, string baselineName = null, bool generatePragmas = true, bool designTimeMode = false, IList <GeneratedCodeMapping> expectedDesignTimePragmas = null, Action <RazorEngineHost> hostConfig = null)
        {
            // Load the test files
            if (baselineName == null)
            {
                baselineName = name;
            }
            string source         = TestFile.Create(String.Format("CodeGenerator.{1}.Source.{0}.{2}", name, LanguageName, FileExtension)).ReadAllText();
            string expectedOutput = TestFile.Create(String.Format("CodeGenerator.{1}.Output.{0}.{2}", baselineName, LanguageName, BaselineExtension)).ReadAllText();

            // Set up the host and engine
            RazorEngineHost host = CreateHost();

            host.NamespaceImports.Add("System");
            host.DesignTimeMode   = designTimeMode;
            host.StaticHelpers    = true;
            host.DefaultClassName = name;

            // Add support for templates, etc.
            host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                                   GeneratedClassContext.DefaultWriteMethodName,
                                                                   GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                                   "WriteTo",
                                                                   "WriteLiteralTo",
                                                                   "Template",
                                                                   "DefineSection",
                                                                   "BeginContext",
                                                                   "EndContext")
            {
                LayoutPropertyName   = "Layout",
                ResolveUrlMethodName = "Href"
            };
            if (hostConfig != null)
            {
                hostConfig(host);
            }

            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            // Generate code for the file
            GeneratorResults results = null;

            using (StringTextBuffer buffer = new StringTextBuffer(source))
            {
                results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null);
            }

            // Generate code
            CodeCompileUnit ccu          = results.GeneratedCode;
            CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType);

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            // Both run-time and design-time use these settings. See:
            // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204
            // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373
            options.BlankLinesBetweenMembers = false;
            options.IndentString             = String.Empty;

            StringBuilder output = new StringBuilder();

            using (StringWriter writer = new StringWriter(output))
            {
                codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options);
            }

            WriteBaseline(String.Format(@"test\System.Web.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.{2}", LanguageName, baselineName, BaselineExtension), MiscUtils.StripRuntimeVersion(output.ToString()));

            // Verify code against baseline
#if !GENERATE_BASELINES
            Assert.Equal(expectedOutput, MiscUtils.StripRuntimeVersion(output.ToString()));
#endif

            // Verify design-time pragmas
            if (designTimeMode)
            {
                Assert.True(expectedDesignTimePragmas != null || results.DesignTimeLineMappings == null || results.DesignTimeLineMappings.Count == 0);
                Assert.True(expectedDesignTimePragmas == null || (results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0));
                if (expectedDesignTimePragmas != null)
                {
                    Assert.Equal(
                        expectedDesignTimePragmas.ToArray(),
                        results.DesignTimeLineMappings
                        .OrderBy(p => p.Key)
                        .Select(p => p.Value)
                        .ToArray());
                }
            }
        }
        protected void AssertCSharpDocumentMatchesBaseline(RazorCodeDocument codeDocument)
        {
            var document = codeDocument.GetCSharpDocument();

            // Normalize newlines to match those in the baseline.
            var actualCode = document.GeneratedCode.Replace("\r", "").Replace("\n", "\r\n");

            var baselineFilePath            = GetBaselineFilePath(codeDocument, ".codegen.cs");
            var baselineDiagnosticsFilePath = GetBaselineFilePath(codeDocument, ".diagnostics.txt");
            var baselineMappingsFilePath    = GetBaselineFilePath(codeDocument, ".mappings.txt");

            var serializedMappings = SourceMappingsSerializer.Serialize(document, codeDocument.Source);

            if (GenerateBaselines)
            {
                var baselineFullPath = Path.Combine(TestProjectRoot, baselineFilePath);
                Directory.CreateDirectory(Path.GetDirectoryName(baselineFullPath));
                WriteBaseline(actualCode, baselineFullPath);

                var baselineDiagnosticsFullPath = Path.Combine(TestProjectRoot, baselineDiagnosticsFilePath);
                var lines = document.Diagnostics.Select(RazorDiagnosticSerializer.Serialize).ToArray();
                if (lines.Any())
                {
                    WriteBaseline(lines, baselineDiagnosticsFullPath);
                }
                else if (File.Exists(baselineDiagnosticsFullPath))
                {
                    File.Delete(baselineDiagnosticsFullPath);
                }

                var baselineMappingsFullPath = Path.Combine(TestProjectRoot, baselineMappingsFilePath);
                var text = SourceMappingsSerializer.Serialize(document, codeDocument.Source);
                if (!string.IsNullOrEmpty(text))
                {
                    WriteBaseline(text, baselineMappingsFullPath);
                }
                else if (File.Exists(baselineMappingsFullPath))
                {
                    File.Delete(baselineMappingsFullPath);
                }

                return;
            }

            var codegenFile = TestFile.Create(baselineFilePath, GetType().Assembly);

            if (!codegenFile.Exists())
            {
                throw new XunitException($"The resource {baselineFilePath} was not found.");
            }

            var baseline = codegenFile.ReadAllText();

            Assert.Equal(baseline, actualCode);

            var baselineDiagnostics = string.Empty;
            var diagnosticsFile     = TestFile.Create(baselineDiagnosticsFilePath, GetType().Assembly);

            if (diagnosticsFile.Exists())
            {
                baselineDiagnostics = diagnosticsFile.ReadAllText();
            }

            var actualDiagnostics = string.Concat(document.Diagnostics.Select(d => RazorDiagnosticSerializer.Serialize(d) + "\r\n"));

            Assert.Equal(baselineDiagnostics, actualDiagnostics);

            var baselineMappings = string.Empty;
            var mappingsFile     = TestFile.Create(baselineMappingsFilePath, GetType().Assembly);

            if (mappingsFile.Exists())
            {
                baselineMappings = mappingsFile.ReadAllText();
            }

            var actualMappings = SourceMappingsSerializer.Serialize(document, codeDocument.Source);

            actualMappings = actualMappings.Replace("\r", "").Replace("\n", "\r\n");
            Assert.Equal(baselineMappings, actualMappings);
        }
示例#11
0
        public void CreateFileWithText()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var file = new TestFile(fileSystem, @"\a\file\this\is.txt");

            // Execute
            file.Create("This is a file!");

            // Assert
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(15, file.Size); // File length determined here: https://mothereff.in/byte-counter#This%20is%20a%20file%21
            Assert.AreEqual(DateTime.UtcNow.Date, file.CreatedTimeUtc.Date);
            Assert.AreEqual(DateTime.UtcNow.Hour, file.CreatedTimeUtc.Hour);
        }
示例#12
0
        private void RunTestInternal(string name,
                                     string baselineName,
                                     bool generatePragmas,
                                     bool designTimeMode,
                                     IList <LineMapping> expectedDesignTimePragmas,
                                     TestSpan[] spans,
                                     bool withTabs,
                                     Func <RazorEngineHost, RazorEngineHost> hostConfig,
                                     Func <RazorTemplateEngine, RazorTemplateEngine> templateEngineConfig,
                                     Action <GeneratorResults> onResults = null)
        {
            // Load the test files
            if (baselineName == null)
            {
                baselineName = name;
            }

            var sourceLocation = string.Format("TestFiles/CodeGenerator/{1}/Source/{0}.{2}", name, LanguageName, FileExtension);
            var expectedOutput = TestFile.Create(string.Format("TestFiles/CodeGenerator/CS/Output/{0}.{1}", baselineName, BaselineExtension)).ReadAllText();

            // Set up the host and engine
            var host = CreateHost();

            host.NamespaceImports.Add("System");
            host.DesignTimeMode   = designTimeMode;
            host.StaticHelpers    = true;
            host.DefaultClassName = name;

            // Add support for templates, etc.
            host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                                   GeneratedClassContext.DefaultWriteMethodName,
                                                                   GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                                   "WriteTo",
                                                                   "WriteLiteralTo",
                                                                   "Template",
                                                                   "DefineSection",
                                                                   "Instrumentation.BeginContext",
                                                                   "Instrumentation.EndContext",
                                                                   new GeneratedTagHelperContext())
            {
                LayoutPropertyName   = "Layout",
                ResolveUrlMethodName = "Href"
            };
            if (hostConfig != null)
            {
                host = hostConfig(host);
            }

            host.IsIndentingWithTabs   = withTabs;
            host.EnableInstrumentation = true;

            var engine = new RazorTemplateEngine(host);

            if (templateEngineConfig != null)
            {
                engine = templateEngineConfig(engine);
            }

            // Generate code for the file
            GeneratorResults results = null;

            using (var source = TestFile.Create(sourceLocation).OpenRead())
            {
                var sourceFileName = generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null;
                results = engine.GenerateCode(source, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: sourceFileName);
            }
            // Only called if GENERATE_BASELINES is set, otherwise compiled out.
            BaselineWriter.WriteBaseline(String.Format(@"test\Microsoft.AspNet.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.{2}", LanguageName, baselineName, BaselineExtension), results.GeneratedCode);

#if !GENERATE_BASELINES
            var textOutput = results.GeneratedCode;

            if (onResults != null)
            {
                onResults(results);
            }

            //// Verify code against baseline
            Assert.Equal(expectedOutput, textOutput);
#endif

            IEnumerable <Span> generatedSpans = results.Document.Flatten();

            foreach (var span in generatedSpans)
            {
                VerifyNoBrokenEndOfLines(span.Content);
            }

            // Verify design-time pragmas
            if (designTimeMode)
            {
                if (spans != null)
                {
                    Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray());
                }

                if (expectedDesignTimePragmas != null)
                {
                    Assert.True(results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0);

                    Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count);

                    for (var i = 0; i < expectedDesignTimePragmas.Count; i++)
                    {
                        if (!expectedDesignTimePragmas[i].Equals(results.DesignTimeLineMappings[i]))
                        {
                            Assert.True(false, String.Format("Line mapping {0} is not equivalent.", i));
                        }
                    }
                }
            }
        }
示例#13
0
        private void RunTestInternal(
            string name,
            string baselineName,
            bool generatePragmas,
            bool designTimeMode,
            IList <LineMapping> expectedDesignTimePragmas,
            TestSpan[] spans,
            bool withTabs,
            Func <RazorEngineHost, RazorEngineHost> hostConfig,
            Func <RazorTemplateEngine, RazorTemplateEngine> templateEngineConfig,
            Action <GeneratorResults> onResults = null)
        {
            // Load the test files
            if (baselineName == null)
            {
                baselineName = name;
            }

            var sourceLocation = string.Format("TestFiles/CodeGenerator/Source/{0}.{1}", name, FileExtension);
            var testFile       = TestFile
                                 .Create(string.Format("TestFiles/CodeGenerator/Output/{0}.{1}", baselineName, BaselineExtension));

            string expectedOutput;

#if GENERATE_BASELINES
            if (testFile.Exists())
            {
                expectedOutput = testFile.ReadAllText();
            }
            else
            {
                expectedOutput = null;
            }
#else
            expectedOutput = testFile.ReadAllText();
#endif

            // Set up the host and engine
            var host = CreateHost();
            host.NamespaceImports.Add("System");
            host.DesignTimeMode   = designTimeMode;
            host.StaticHelpers    = true;
            host.DefaultClassName = name;

            // Add support for templates, etc.
            host.GeneratedClassContext = new GeneratedClassContext(
                GeneratedClassContext.DefaultExecuteMethodName,
                GeneratedClassContext.DefaultWriteMethodName,
                GeneratedClassContext.DefaultWriteLiteralMethodName,
                "WriteTo",
                "WriteLiteralTo",
                "Template",
                "DefineSection",
                "Instrumentation.BeginContext",
                "Instrumentation.EndContext",
                new GeneratedTagHelperContext());
            if (hostConfig != null)
            {
                host = hostConfig(host);
            }

            host.IsIndentingWithTabs   = withTabs;
            host.EnableInstrumentation = true;

            var engine = new RazorTemplateEngine(host);

            if (templateEngineConfig != null)
            {
                engine = templateEngineConfig(engine);
            }

            // Generate code for the file
            GeneratorResults results = null;
            using (var source = TestFile.Create(sourceLocation).OpenRead())
            {
                var sourceFile     = NormalizeNewLines(source);
                var sourceFileName = generatePragmas ? string.Format("{0}.{1}", name, FileExtension) : null;
                results = engine.GenerateCode(
                    sourceFile,
                    className: name,
                    rootNamespace: TestRootNamespaceName,
                    sourceFileName: sourceFileName);
            }

            var textOutput = results.GeneratedCode;
#if GENERATE_BASELINES
            var outputFile = string.Format(
                @"test\Microsoft.AspNet.Razor.Test\TestFiles\CodeGenerator\Output\{0}.{1}",
                baselineName,
                BaselineExtension);

            // Update baseline files if files do not already match.
            if (!string.Equals(expectedOutput, textOutput, StringComparison.Ordinal))
            {
                BaselineWriter.WriteBaseline(outputFile, textOutput);
            }
#else
            if (onResults != null)
            {
                onResults(results);
            }

            // Verify code against baseline
            Assert.Equal(expectedOutput, textOutput);
#endif

            var generatedSpans = results.Document.Flatten();

            foreach (var span in generatedSpans)
            {
                VerifyNoBrokenEndOfLines(span.Content);
            }

            // Verify design-time pragmas
            if (designTimeMode)
            {
                if (spans != null)
                {
                    Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray());
                }

                if (expectedDesignTimePragmas != null)
                {
                    Assert.NotNull(results.DesignTimeLineMappings); // Guard
#if GENERATE_BASELINES
                    if (expectedDesignTimePragmas == null ||
                        !Enumerable.SequenceEqual(expectedDesignTimePragmas, results.DesignTimeLineMappings))
                    {
                        var lineMappingFile = Path.ChangeExtension(outputFile, "lineMappings.cs");
                        var lineMappingCode = GetDesignTimeLineMappingsCode(results.DesignTimeLineMappings);
                        BaselineWriter.WriteBaseline(lineMappingFile, lineMappingCode);
                    }
#else
                    for (var i = 0; i < expectedDesignTimePragmas.Count && i < results.DesignTimeLineMappings.Count; i++)
                    {
                        Assert.Equal(expectedDesignTimePragmas[i], results.DesignTimeLineMappings[i]);
                    }

                    Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count);
#endif
                }
            }
        }
        internal virtual void AssertSyntaxTreeNodeMatchesBaseline(RazorSyntaxTree syntaxTree)
        {
            var root        = syntaxTree.Root;
            var diagnostics = syntaxTree.Diagnostics;
            var filePath    = syntaxTree.Source.FilePath;

            if (FileName == null)
            {
                var message = $"{nameof(AssertSyntaxTreeNodeMatchesBaseline)} should only be called from a parser test ({nameof(FileName)} is null).";
                throw new InvalidOperationException(message);
            }

            if (IsTheory)
            {
                var message = $"{nameof(AssertSyntaxTreeNodeMatchesBaseline)} should not be called from a [Theory] test.";
                throw new InvalidOperationException(message);
            }

            var fileName                        = BaselineTestCount > 0 ? FileName + $"_{BaselineTestCount}" : FileName;
            var baselineFileName                = Path.ChangeExtension(fileName, ".stree.txt");
            var baselineDiagnosticsFileName     = Path.ChangeExtension(fileName, ".diag.txt");
            var baselineClassifiedSpansFileName = Path.ChangeExtension(fileName, ".cspans.txt");
            var baselineTagHelperSpansFileName  = Path.ChangeExtension(fileName, ".tspans.txt");

            BaselineTestCount++;

            if (GenerateBaselines)
            {
                // Write syntax tree baseline
                var baselineFullPath = Path.Combine(TestProjectRoot, baselineFileName);
                File.WriteAllText(baselineFullPath, SyntaxNodeSerializer.Serialize(root));

                // Write diagnostics baseline
                var baselineDiagnosticsFullPath = Path.Combine(TestProjectRoot, baselineDiagnosticsFileName);
                var lines = diagnostics.Select(SerializeDiagnostic).ToArray();
                if (lines.Any())
                {
                    File.WriteAllLines(baselineDiagnosticsFullPath, lines);
                }
                else if (File.Exists(baselineDiagnosticsFullPath))
                {
                    File.Delete(baselineDiagnosticsFullPath);
                }

                // Write classified spans baseline
                var classifiedSpansBaselineFullPath = Path.Combine(TestProjectRoot, baselineClassifiedSpansFileName);
                File.WriteAllText(classifiedSpansBaselineFullPath, ClassifiedSpanSerializer.Serialize(syntaxTree));

                // Write tag helper spans baseline
                var tagHelperSpansBaselineFullPath = Path.Combine(TestProjectRoot, baselineTagHelperSpansFileName);
                var serializedTagHelperSpans       = TagHelperSpanSerializer.Serialize(syntaxTree);
                if (!string.IsNullOrEmpty(serializedTagHelperSpans))
                {
                    File.WriteAllText(tagHelperSpansBaselineFullPath, serializedTagHelperSpans);
                }
                else if (File.Exists(tagHelperSpansBaselineFullPath))
                {
                    File.Delete(tagHelperSpansBaselineFullPath);
                }

                return;
            }

            // Verify syntax tree
            var stFile = TestFile.Create(baselineFileName, GetType().GetTypeInfo().Assembly);

            if (!stFile.Exists())
            {
                throw new XunitException($"The resource {baselineFileName} was not found.");
            }

            var baseline = stFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            SyntaxNodeVerifier.Verify(root, baseline);

            // Verify diagnostics
            var baselineDiagnostics = string.Empty;
            var diagnosticsFile     = TestFile.Create(baselineDiagnosticsFileName, GetType().GetTypeInfo().Assembly);

            if (diagnosticsFile.Exists())
            {
                baselineDiagnostics = diagnosticsFile.ReadAllText();
            }

            var actualDiagnostics = string.Concat(diagnostics.Select(d => SerializeDiagnostic(d) + "\r\n"));

            Assert.Equal(baselineDiagnostics, actualDiagnostics);

            // Verify classified spans
            var classifiedSpanFile = TestFile.Create(baselineClassifiedSpansFileName, GetType().GetTypeInfo().Assembly);

            if (!classifiedSpanFile.Exists())
            {
                throw new XunitException($"The resource {baselineClassifiedSpansFileName} was not found.");
            }
            else
            {
                var classifiedSpanBaseline = Array.Empty <string>();
                classifiedSpanBaseline = classifiedSpanFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                ClassifiedSpanVerifier.Verify(syntaxTree, classifiedSpanBaseline);
            }

            // Verify tag helper spans
            var tagHelperSpanFile     = TestFile.Create(baselineTagHelperSpansFileName, GetType().GetTypeInfo().Assembly);
            var tagHelperSpanBaseline = Array.Empty <string>();

            if (tagHelperSpanFile.Exists())
            {
                tagHelperSpanBaseline = tagHelperSpanFile.ReadAllText().Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                TagHelperSpanVerifier.Verify(syntaxTree, tagHelperSpanBaseline);
            }
        }
示例#15
0
        public void DeleteFile()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var file = new TestFile(fileSystem, "\\this\\is\\a\\file.txt");
            var stream = new MemoryStream();
            file.Create(stream);

            // Execute
            file.Delete();

            // Assert
            Assert.IsFalse(file.Exists);
        }
示例#16
0
        public void CreateFileWithNullStream()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var file = new TestFile(fileSystem, "\\this\\is\\a\\file.txt");

            // Execute
            file.Create(a_contents: null);
        }
示例#17
0
        protected void RunTest(string name, string baselineName = null, bool generatePragmas = true, bool designTimeMode = false, IList <LinePragmaCodeInfo> expectedDesignTimePragmas = null, Action <RazorEngineHost> hostConfig = null)
        {
            // Load the test files
            if (baselineName == null)
            {
                baselineName = name;
            }
            string source         = TestFile.Create(String.Format("CodeGenerator.{1}.Source.{0}.{2}", name, LanguageName, FileExtension)).ReadAllText();
            string expectedOutput = TestFile.Create(String.Format("CodeGenerator.{1}.Output.{0}.txt", baselineName, LanguageName)).ReadAllText();

            // Set up the host and engine
            RazorEngineHost host = CreateHost();

            host.NamespaceImports.Add("System");
            host.DesignTimeMode = designTimeMode;
            host.StaticHelpers  = true;
            if (hostConfig != null)
            {
                hostConfig(host);
            }

            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            // Add support for templates, etc.
            host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName,
                                                                   GeneratedClassContext.DefaultWriteMethodName,
                                                                   GeneratedClassContext.DefaultWriteLiteralMethodName,
                                                                   "WriteTo",
                                                                   "WriteLiteralTo",
                                                                   "Template",
                                                                   "DefineSection");

            // Generate code for the file
            GeneratorResults results = null;

            using (StringTextBuffer buffer = new StringTextBuffer(source)) {
                results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null);
            }


            // Generate code
            CodeCompileUnit ccu          = results.GeneratedCode;
            CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType);

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            // Both run-time and design-time use these settings. See:
            // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204
            // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373
            options.BlankLinesBetweenMembers = false;
            options.IndentString             = string.Empty;

            StringBuilder output = new StringBuilder();

            using (StringWriter writer = new StringWriter(output)) {
                codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options);
            }

#if GENERATE_BASELINES
            // Update baseline
            // IMPORTANT! Replace this path with the local path on your machine to the baseline files!
            string baselineFile = String.Format(@"D:\dd\Plan9\Main\test\System.Web.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.txt", LanguageName, baselineName);
            File.Delete(baselineFile);
            File.WriteAllText(baselineFile, MiscUtils.StripRuntimeVersion(output.ToString()));
#else
            // Verify code against baseline
            Assert.AreEqual(expectedOutput, MiscUtils.StripRuntimeVersion(output.ToString()));
#endif

            // Verify design-time pragmas
            if (designTimeMode)
            {
                Assert.IsTrue(expectedDesignTimePragmas != null || results.DesignTimeLineMappings == null || results.DesignTimeLineMappings.Count == 0);
                Assert.IsTrue(expectedDesignTimePragmas == null || (results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0));
                Enumerable.Zip(expectedDesignTimePragmas, results.DesignTimeLineMappings, (expected, actual) => {
                    Assert.AreEqual(expected.CodeLength, actual.Value.CodeLength, "CodeLength values are not equal for pragma {0}!", actual.Key);
                    Assert.AreEqual(expected.StartColumn, actual.Value.StartColumn, "StartColumn values are not equal for pragma {0}!", actual.Key);
                    Assert.AreEqual(expected.StartGeneratedColumn, actual.Value.StartGeneratedColumn, "StartGeneratedColumn values are not equal for pragma {0}!", actual.Key);
                    Assert.AreEqual(expected.StartLine, actual.Value.StartLine, "StartLine values are not equal for pragma {0}!", actual.Key);
                    return((object)null);
                }).ToList();
                Assert.AreEqual(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count);
            }
        }
示例#18
0
        private RazorDocumentRangeFormattingResponse Format(RazorDocumentRangeFormattingParams @params)
        {
            if (@params.Kind == RazorLanguageKind.Razor)
            {
                throw new InvalidOperationException("We shouldn't be asked to format Razor language kind.");
            }

            var options  = @params.Options;
            var response = new RazorDocumentRangeFormattingResponse();

            if (@params.Kind == RazorLanguageKind.CSharp)
            {
                var codeDocument     = _documents[@params.HostDocumentFilePath];
                var csharpSourceText = codeDocument.GetCSharpSourceText();
                var csharpDocument   = GetCSharpDocument(codeDocument, @params.Options);
                if (!csharpDocument.TryGetSyntaxRoot(out var root))
                {
                    throw new InvalidOperationException("Couldn't get syntax root.");
                }
                var spanToFormat = @params.ProjectedRange.AsTextSpan(csharpSourceText);

                var changes = Formatter.GetFormattedTextChanges(root, spanToFormat, csharpDocument.Project.Solution.Workspace);

                response.Edits = changes.Select(c => c.AsTextEdit(csharpSourceText)).ToArray();
            }
            else if (@params.Kind == RazorLanguageKind.Html)
            {
                response.Edits = Array.Empty <TextEdit>();

                var codeDocument  = _documents[@params.HostDocumentFilePath];
                var generatedHtml = codeDocument.GetHtmlDocument().GeneratedHtml;
                generatedHtml = generatedHtml.Replace("\r", "", StringComparison.Ordinal).Replace("\n", "\r\n", StringComparison.Ordinal);

                // Get formatted baseline file
                var baselineInputFileName  = Path.ChangeExtension(_baselineFileName, ".input.html");
                var baselineOutputFileName = Path.ChangeExtension(_baselineFileName, ".output.html");

                var baselineInputFile  = TestFile.Create(baselineInputFileName, GetType().GetTypeInfo().Assembly);
                var baselineOutputFile = TestFile.Create(baselineOutputFileName, GetType().GetTypeInfo().Assembly);

                if (GenerateBaselines)
                {
                    if (baselineInputFile.Exists())
                    {
                        // If it already exists, we only want to update if the input is different.
                        var inputContent = baselineInputFile.ReadAllText();
                        if (string.Equals(inputContent, generatedHtml, StringComparison.Ordinal))
                        {
                            return(response);
                        }
                    }

                    var baselineInputFilePath = Path.Combine(_projectPath, baselineInputFileName);
                    File.WriteAllText(baselineInputFilePath, generatedHtml);

                    var baselineOutputFilePath = Path.Combine(_projectPath, baselineOutputFileName);
                    File.WriteAllText(baselineOutputFilePath, generatedHtml);

                    return(response);
                }

                if (!baselineInputFile.Exists())
                {
                    throw new XunitException($"The resource {baselineInputFileName} was not found.");
                }

                if (!baselineOutputFile.Exists())
                {
                    throw new XunitException($"The resource {baselineOutputFileName} was not found.");
                }

                var baselineInputHtml = baselineInputFile.ReadAllText();
                if (!string.Equals(baselineInputHtml, generatedHtml, StringComparison.Ordinal))
                {
                    throw new XunitException($"The baseline for {_baselineFileName} is out of date.");
                }

                var baselineOutputHtml = baselineOutputFile.ReadAllText();
                var baselineInputText  = SourceText.From(baselineInputHtml);
                var baselineOutputText = SourceText.From(baselineOutputHtml);
                var changes            = SourceTextDiffer.GetMinimalTextChanges(baselineInputText, baselineOutputText, lineDiffOnly: false);
                var edits = changes.Select(c => c.AsTextEdit(baselineInputText)).ToArray();
                response.Edits = edits;
            }

            return(response);
        }
示例#19
0
        public void SetValue(TestImageWriteFormat imageFormat, int expectedProfileValueCount)
        {
            Image <Rgba32> image = TestFile.Create(TestImages.Jpeg.Baseline.Floorplan).CreateRgba32Image();

            image.Metadata.ExifProfile.SetValue(ExifTag.Software, "ImageSharp");

            IExifValue <string> software = image.Metadata.ExifProfile.GetValue(ExifTag.Software);

            Assert.Equal("ImageSharp", software.Value);

            // ExifString can set integer values.
            Assert.True(software.TrySetValue(15));
            Assert.False(software.TrySetValue(15F));

            image.Metadata.ExifProfile.SetValue(ExifTag.ShutterSpeedValue, new SignedRational(75.55));

            IExifValue <SignedRational> shutterSpeed = image.Metadata.ExifProfile.GetValue(ExifTag.ShutterSpeedValue);

            Assert.Equal(new SignedRational(7555, 100), shutterSpeed.Value);
            Assert.False(shutterSpeed.TrySetValue(75));

            image.Metadata.ExifProfile.SetValue(ExifTag.XResolution, new Rational(150.0));

            // We also need to change this value because this overrides XResolution when the image is written.
            image.Metadata.HorizontalResolution = 150.0;

            IExifValue <Rational> xResolution = image.Metadata.ExifProfile.GetValue(ExifTag.XResolution);

            Assert.Equal(new Rational(150, 1), xResolution.Value);

            Assert.False(xResolution.TrySetValue("ImageSharp"));

            image.Metadata.ExifProfile.SetValue(ExifTag.ReferenceBlackWhite, null);

            IExifValue <Rational[]> referenceBlackWhite = image.Metadata.ExifProfile.GetValue(ExifTag.ReferenceBlackWhite);

            Assert.Null(referenceBlackWhite.Value);

            var expectedLatitude = new Rational[] { new Rational(12.3), new Rational(4.56), new Rational(789.0) };

            image.Metadata.ExifProfile.SetValue(ExifTag.GPSLatitude, expectedLatitude);

            IExifValue <Rational[]> latitude = image.Metadata.ExifProfile.GetValue(ExifTag.GPSLatitude);

            Assert.Equal(expectedLatitude, latitude.Value);

            // todo: duplicate tags
            Assert.Equal(2, image.Metadata.ExifProfile.Values.Count(v => (ushort)v.Tag == 59932));

            image = WriteAndRead(image, imageFormat);

            Assert.NotNull(image.Metadata.ExifProfile);
            Assert.Equal(0, image.Metadata.ExifProfile.Values.Count(v => (ushort)v.Tag == 59932));

            Assert.Equal(expectedProfileValueCount, image.Metadata.ExifProfile.Values.Count);

            software = image.Metadata.ExifProfile.GetValue(ExifTag.Software);
            Assert.Equal("15", software.Value);

            shutterSpeed = image.Metadata.ExifProfile.GetValue(ExifTag.ShutterSpeedValue);
            Assert.Equal(new SignedRational(75.55), shutterSpeed.Value);

            xResolution = image.Metadata.ExifProfile.GetValue(ExifTag.XResolution);
            Assert.Equal(new Rational(150.0), xResolution.Value);

            referenceBlackWhite = image.Metadata.ExifProfile.GetValue(ExifTag.ReferenceBlackWhite);
            Assert.Null(referenceBlackWhite);

            latitude = image.Metadata.ExifProfile.GetValue(ExifTag.GPSLatitude);
            Assert.Equal(expectedLatitude, latitude.Value);

            image.Dispose();
        }
示例#20
0
            private Image <TPixel> LoadImage(IImageDecoder decoder)
            {
                var testFile = TestFile.Create(this.FilePath);

                return(Image.Load <TPixel>(this.Configuration, testFile.Bytes, decoder));
            }
示例#21
0
        public void CreateFileWithNullText()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var file = new TestFile(fileSystem, @"\a\file\this\is.txt");

            // Execute
            file.Create(a_text: null);
        }
示例#22
0
        public void ExcludeFilter_Works(object filterObj)
        {
            // arrange
            var chunkFilter = (PngChunkFilter)filterObj;
            var testFile    = TestFile.Create(TestImages.Png.PngWithMetadata);

            using Image <Rgba32> input = testFile.CreateRgba32Image();
            using var memStream = new MemoryStream();
            var encoder = new PngEncoder()
            {
                ChunkFilter = chunkFilter, TextCompressionThreshold = 8
            };
            var expectedChunkTypes = new Dictionary <PngChunkType, bool>()
            {
                { PngChunkType.Header, false },
                { PngChunkType.Gamma, false },
                { PngChunkType.Palette, false },
                { PngChunkType.InternationalText, false },
                { PngChunkType.Text, false },
                { PngChunkType.CompressedText, false },
                { PngChunkType.Exif, false },
                { PngChunkType.Physical, false },
                { PngChunkType.Data, false },
                { PngChunkType.End, false }
            };
            var excludedChunkTypes = new List <PngChunkType>();

            switch (chunkFilter)
            {
            case PngChunkFilter.ExcludeGammaChunk:
                excludedChunkTypes.Add(PngChunkType.Gamma);
                expectedChunkTypes.Remove(PngChunkType.Gamma);
                break;

            case PngChunkFilter.ExcludeExifChunk:
                excludedChunkTypes.Add(PngChunkType.Exif);
                expectedChunkTypes.Remove(PngChunkType.Exif);
                break;

            case PngChunkFilter.ExcludePhysicalChunk:
                excludedChunkTypes.Add(PngChunkType.Physical);
                expectedChunkTypes.Remove(PngChunkType.Physical);
                break;

            case PngChunkFilter.ExcludeTextChunks:
                excludedChunkTypes.Add(PngChunkType.Text);
                excludedChunkTypes.Add(PngChunkType.InternationalText);
                excludedChunkTypes.Add(PngChunkType.CompressedText);
                expectedChunkTypes.Remove(PngChunkType.Text);
                expectedChunkTypes.Remove(PngChunkType.InternationalText);
                expectedChunkTypes.Remove(PngChunkType.CompressedText);
                break;

            case PngChunkFilter.ExcludeAll:
                excludedChunkTypes.Add(PngChunkType.Gamma);
                excludedChunkTypes.Add(PngChunkType.Exif);
                excludedChunkTypes.Add(PngChunkType.Physical);
                excludedChunkTypes.Add(PngChunkType.Text);
                excludedChunkTypes.Add(PngChunkType.InternationalText);
                excludedChunkTypes.Add(PngChunkType.CompressedText);
                expectedChunkTypes.Remove(PngChunkType.Gamma);
                expectedChunkTypes.Remove(PngChunkType.Exif);
                expectedChunkTypes.Remove(PngChunkType.Physical);
                expectedChunkTypes.Remove(PngChunkType.Text);
                expectedChunkTypes.Remove(PngChunkType.InternationalText);
                expectedChunkTypes.Remove(PngChunkType.CompressedText);
                break;
            }

            // act
            input.Save(memStream, encoder);

            // assert
            Assert.True(excludedChunkTypes.Count > 0);
            memStream.Position = 0;
            Span <byte> bytesSpan = memStream.ToArray().AsSpan(8); // Skip header.

            while (bytesSpan.Length > 0)
            {
                int length    = BinaryPrimitives.ReadInt32BigEndian(bytesSpan.Slice(0, 4));
                var chunkType = (PngChunkType)BinaryPrimitives.ReadInt32BigEndian(bytesSpan.Slice(4, 4));
                Assert.False(excludedChunkTypes.Contains(chunkType), $"{chunkType} chunk should have been excluded");
                if (expectedChunkTypes.ContainsKey(chunkType))
                {
                    expectedChunkTypes[chunkType] = true;
                }

                bytesSpan = bytesSpan.Slice(4 + 4 + length + 4);
            }

            // all expected chunk types should have been seen at least once.
            foreach (PngChunkType chunkType in expectedChunkTypes.Keys)
            {
                Assert.True(expectedChunkTypes[chunkType], $"We expect {chunkType} chunk to be present at least once");
            }
        }
示例#23
0
        public void Create()
        {
            var testFile = TestFile.Create(typeof(TestFileTest).Assembly, string.Empty);

            Assert.True(File.Exists(testFile.SourceFilePath));
        }
示例#24
0
        public void TestBackupSync()
        {
            string rootWorkingDir = Path.Combine(testRoot, "BackupSyncBase");

            var dirs = TestDirectory.Create(rootWorkingDir);

            string rootSourceDir = dirs.Item1;
            string rootTargetDir = dirs.Item2;

            // Create settings
            BackupSettings settings = new()
            {
                IgnoreHiddenFiles = false,
                TargetDirectory   = rootTargetDir,
                SourceDirectories = new string[] { rootSourceDir }
            };

            BackupTaskSync task = new()
            {
                RetryEnabled         = false,
                MinFileWriteWaitTime = 0
            };

            // Add handler to main copy test for debugging output
            task.Log += Task_Log;

            /////////////////////////////////////
            // Copy files
            /////////////////////////////////////
            int filesCopied = task.Run(settings);

            // Filter source files that should have been copied
            var sourceFiles = Directory.EnumerateFiles(rootSourceDir, "*.*", SearchOption.AllDirectories);

            // Check task returned expected number of files
            Assert.AreEqual(sourceFiles.Count(), filesCopied);

            // Compare directories
            int targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Run copy again
            /////////////////////////////////////
            filesCopied = task.Run(settings);

            // Should be no new copies - nothing changed
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Add files, run copy again
            /////////////////////////////////////
            // Add first file to root
            string addedFile1 = Path.Combine(rootSourceDir, "added-file1.txt");

            TestFile.Create(addedFile1);

            // Add second file to a new sub dir
            DirectoryInfo addedDirInfo = Directory.CreateDirectory(Path.Combine(rootSourceDir, "added-dir"));
            string        addedFile2   = Path.Combine(addedDirInfo.FullName, "added-file2.txt");

            TestFile.Create(addedFile2);

            // Run backup again
            filesCopied = task.Run(settings);

            // Only the new files should be copied
            Assert.AreEqual(2, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Modify file, run copy again
            /////////////////////////////////////
            TestFile.Modify(addedFile1);

            filesCopied = task.Run(settings);

            // Should only be modified file copied
            Assert.AreEqual(1, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Delete file, run copy again
            /////////////////////////////////////
            File.Delete(addedFile1);

            filesCopied = task.Run(settings);

            // Should be nothing added, new file removed from target
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // File should also have been deleted from target
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Delete directory, run copy again
            /////////////////////////////////////
            addedDirInfo.Delete(true);

            filesCopied = task.Run(settings);

            // Should be nothing added
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Dir and contents should also have been deleted from target
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Change hidden files, run copy again
            /////////////////////////////////////
            settings.IgnoreHiddenFiles = true;

            // Return non-hidden
            static bool sourceFilter(string f) => !File.GetAttributes(f).HasFlag(FileAttributes.Hidden) && !new DirectoryInfo(Path.GetDirectoryName(f) !).Attributes.HasFlag(FileAttributes.Hidden);

            // Refresh expected source files
            sourceFiles = Directory.EnumerateFiles(rootSourceDir, "*.*", SearchOption.AllDirectories).Where(sourceFilter);

            // Run task again
            filesCopied = task.Run(settings);

            // Should be nothing added
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Dir and contents should also have been deleted from target
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            // Remove handler
            task.Log -= Task_Log;
        }
        protected void AssertSourceMappingsMatchBaseline(RazorCodeDocument codeDocument)
        {
            if (FileName == null)
            {
                var message = $"{nameof(AssertSourceMappingsMatchBaseline)} should only be called from an integration test ({nameof(FileName)} is null).";
                throw new InvalidOperationException(message);
            }

            var csharpDocument = codeDocument.GetCSharpDocument();

            Assert.NotNull(csharpDocument);

            var baselineFileName   = Path.ChangeExtension(FileName, ".mappings.txt");
            var serializedMappings = SourceMappingsSerializer.Serialize(csharpDocument, codeDocument.Source);

            if (GenerateBaselines)
            {
                var baselineFullPath = Path.Combine(TestProjectRoot, baselineFileName);
                File.WriteAllText(baselineFullPath, serializedMappings);
                return;
            }

            var testFile = TestFile.Create(baselineFileName, GetType().GetTypeInfo().Assembly);

            if (!testFile.Exists())
            {
                throw new XunitException($"The resource {baselineFileName} was not found.");
            }

            var baseline = testFile.ReadAllText();

            // Normalize newlines to match those in the baseline.
            var actualBaseline = serializedMappings.Replace("\r", "").Replace("\n", "\r\n");

            Assert.Equal(baseline, actualBaseline);

            var syntaxTree = codeDocument.GetSyntaxTree();
            var visitor    = new CodeSpanVisitor();

            visitor.Visit(syntaxTree.Root);

            var charBuffer = new char[codeDocument.Source.Length];

            codeDocument.Source.CopyTo(0, charBuffer, 0, codeDocument.Source.Length);
            var sourceContent = new string(charBuffer);

            var spans = visitor.CodeSpans;

            for (var i = 0; i < spans.Count; i++)
            {
                var span       = spans[i];
                var sourceSpan = span.GetSourceSpan(codeDocument.Source);
                if (sourceSpan == null)
                {
                    // Not in the main file, skip.
                    continue;
                }

                var expectedSpan = sourceContent.Substring(sourceSpan.AbsoluteIndex, sourceSpan.Length);

                // See #2593
                if (string.IsNullOrWhiteSpace(expectedSpan))
                {
                    // For now we don't verify whitespace inside of a directive. We know that directives cheat
                    // with how they bound whitespace/C#/markup to make completion work.
                    if (span.FirstAncestorOrSelf <RazorDirectiveSyntax>() != null)
                    {
                        continue;
                    }
                }

                // See #2594
                if (string.Equals("@", expectedSpan))
                {
                    // For now we don't verify an escaped transition. In some cases one of the @ tokens in @@foo
                    // will be mapped as C# but will not be present in the output buffer because it's not actually C#.
                    continue;
                }

                var found = false;
                for (var j = 0; j < csharpDocument.SourceMappings.Count; j++)
                {
                    var mapping = csharpDocument.SourceMappings[j];
                    if (mapping.OriginalSpan == sourceSpan)
                    {
                        var actualSpan = csharpDocument.GeneratedCode.Substring(
                            mapping.GeneratedSpan.AbsoluteIndex,
                            mapping.GeneratedSpan.Length);

                        if (!string.Equals(expectedSpan, actualSpan, StringComparison.Ordinal))
                        {
                            throw new XunitException(
                                      $"Found the span {sourceSpan} in the output mappings but it contains " +
                                      $"'{EscapeWhitespace(actualSpan)}' instead of '{EscapeWhitespace(expectedSpan)}'.");
                        }

                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    throw new XunitException(
                              $"Could not find the span {sourceSpan} - containing '{EscapeWhitespace(expectedSpan)}' " +
                              $"in the output.");
                }
            }
        }
示例#26
0
        public void CreateFile()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var file = new TestFile(fileSystem, "\\this\\is\\a\\file.txt");
            var stream = new MemoryStream(new byte[1234]);

            // Execute
            file.Create(stream);

            // Assert
            Assert.IsTrue(file.Exists);
            Assert.AreEqual(1234, file.Size);
            Assert.AreEqual(DateTime.UtcNow.Date, file.CreatedTimeUtc.Date);
            Assert.AreEqual(DateTime.UtcNow.Hour, file.CreatedTimeUtc.Hour);
        }
        public void TestBackupCopy()
        {
            string rootWorkingDir = Path.Combine(testRoot, "BackupCopyBase");

            var dirs = TestDirectory.Create(rootWorkingDir);

            string rootSourceDir = dirs.Item1;
            string rootTargetDir = dirs.Item2;

            // Create settings
            BackupSettings settings = new()
            {
                IgnoreHiddenFiles = false,
                TargetDirectory   = rootTargetDir,
                SourceDirectories = new string[] { rootSourceDir }
            };

            BackupTaskCopy task = new()
            {
                RetryEnabled         = false,
                MinFileWriteWaitTime = 0
            };

            // Add handler to main copy test for debugging output
            task.Log += Task_Log;

            /////////////////////////////////////
            // Copy files
            /////////////////////////////////////
            int filesCopied = task.Run(settings);

            // Filter source files that should have been copied
            var sourceFiles = Directory.EnumerateFiles(rootSourceDir, "*.*", SearchOption.AllDirectories);

            // Check task returned expected number of files
            Assert.AreEqual(sourceFiles.Count(), filesCopied);

            // Compare directories
            int targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Run copy again
            /////////////////////////////////////
            filesCopied = task.Run(settings);

            // Should be no new copies - nothing changed
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Add files, run copy again
            /////////////////////////////////////
            // Add first file to root
            string addedFile1 = Path.Combine(rootSourceDir, "added-file1.txt");

            TestFile.Create(addedFile1);

            // Add second file to a new sub dir
            DirectoryInfo addedDirInfo = Directory.CreateDirectory(Path.Combine(rootSourceDir, "added-dir"));
            string        addedFile2   = Path.Combine(addedDirInfo.FullName, "added-file2.txt");

            TestFile.Create(addedFile2);

            // Run backup again
            filesCopied = task.Run(settings);

            // Only the new files should be copied
            Assert.AreEqual(2, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Modify file, run copy again
            /////////////////////////////////////
            TestFile.Modify(addedFile1);

            filesCopied = task.Run(settings);

            // Should only be modified file copied
            Assert.AreEqual(1, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Check expected number of files were copied
            Assert.AreEqual(sourceFiles.Count(), targetCount);

            /////////////////////////////////////
            // Delete file, run copy again
            /////////////////////////////////////
            File.Delete(addedFile1);

            filesCopied = task.Run(settings);

            // Should be nothing changed, added file remains in target
            Assert.AreEqual(0, filesCopied);

            // Compare directories
            targetCount = VerifyBackup(sourceFiles, rootTargetDir);

            // Target should have one more file than source
            Assert.AreEqual(sourceFiles.Count() + 1, targetCount);

            // Remove handler
            task.Log -= Task_Log;
        }

        [TestMethod]
示例#28
0
        public void SetPropertiesOnMessageTest_SetsAllInfoCorrectlyOnMailMessageTest()
        {
            // Arrange
            MailMessage message         = new MailMessage();
            string      to              = "*****@*****.**";
            string      subject         = "subject1";
            string      body            = "body1";
            string      from            = FromAddress;
            string      cc              = "*****@*****.**";
            string      attachmentName  = "NETLogo.png";
            string      bcc             = "*****@*****.**";
            string      replyTo         = "[email protected],[email protected]";
            string      contentEncoding = "utf-8";
            string      headerEncoding  = "utf-16";
            var         priority        = MailPriority.Low;

            // Act
            string fileToAttach = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                TestFile.Create(attachmentName).Save(fileToAttach);
                bool isBodyHtml        = true;
                var  additionalHeaders = new[] { "header1:value1" };
                WebMail.SetPropertiesOnMessage(
                    message,
                    to,
                    subject,
                    body,
                    from,
                    cc,
                    bcc,
                    replyTo,
                    contentEncoding,
                    headerEncoding,
                    priority,
                    new[] { fileToAttach },
                    isBodyHtml,
                    additionalHeaders
                    );

                // Assert
                Assert.Equal(body, message.Body);
                Assert.Equal(subject, message.Subject);
                Assert.Equal(to, message.To[0].Address);
                Assert.Equal(cc, message.CC[0].Address);
                Assert.Equal(from, message.From.Address);
                Assert.Equal(bcc, message.Bcc[0].Address);
                Assert.Equal("*****@*****.**", message.ReplyToList[0].Address);
                Assert.Equal("*****@*****.**", message.ReplyToList[1].Address);
                Assert.Equal(MailPriority.Low, message.Priority);
                Assert.Equal(Encoding.UTF8, message.BodyEncoding);
                Assert.Equal(Encoding.Unicode, message.HeadersEncoding);

                Assert.Contains("header1", message.Headers.AllKeys);
                Assert.Single(message.Attachments);
            }
            finally
            {
                try
                {
                    File.Delete(fileToAttach);
                }
                catch (IOException) { } // Try our best to clean up after ourselves
            }
        }