Пример #1
0

        
Пример #2
0
        public void FromRoute_Globbing_WithProcessors_Success(string pattern, string path)
        {
            var pipeline = new AssetPipeline();

            pipeline.AddFiles("text/css", pattern).MinifyCss();

            Assert.True(pipeline.TryGetAssetFromRoute(path, out var a1));
            Assert.Equal(1, a1.Processors.Count);
        }
Пример #3
0

        
Пример #4
0

        
Пример #5
0

        
Пример #6
0
        public async Task AssetMiddleware_NoCache()
        {
            string cssContent = "*{color:red}";

            var pipeline = new AssetPipeline();
            var options  = new WebOptimizerOptions()
            {
                EnableCaching = false
            };
            var asset = new Mock <IAsset>().SetupAllProperties();

            asset.SetupGet(a => a.ContentType).Returns("text/css");
            asset.SetupGet(a => a.Route).Returns("/file.css");
            asset.Setup(a => a.ExecuteAsync(It.IsAny <HttpContext>(), options))
            .Returns(Task.FromResult(cssContent.AsByteArray()));

            StringValues values;
            var          response = new Mock <HttpResponse>().SetupAllProperties();
            var          context  = new Mock <HttpContext>().SetupAllProperties();

            context.Setup(s => s.Request.Headers.TryGetValue("Accept-Encoding", out values))
            .Returns(false);
            context.Setup(c => c.Response)
            .Returns(response.Object);

            context.Setup(c => c.Request.Path).Returns("/file.css");
            context.Setup(c => c.Features.Get <IHttpsCompressionFeature>()).Returns((IHttpsCompressionFeature)null);

            response.SetupGet(c => c.Headers)
            .Returns(new HeaderDictionary());

            var next  = new Mock <RequestDelegate>();
            var env   = new HostingEnvironment();
            var cache = new Mock <IMemoryCache>();

            pipeline._assets = new ConcurrentDictionary <string, IAsset>();
            pipeline._assets.TryAdd(asset.Object.Route, asset.Object);

            var amo = new Mock <IOptionsSnapshot <WebOptimizerOptions> >();

            amo.SetupGet(a => a.Value).Returns(options);

            var mcr     = new AssetResponse(cssContent.AsByteArray(), null);
            var logger  = new Mock <ILogger <AssetMiddleware> >();
            var builder = new Mock <IAssetBuilder>();

            builder.Setup(b => b.BuildAsync(It.IsAny <IAsset>(), context.Object, options)).Returns(Task.FromResult <IAssetResponse>(mcr));
            var middleware = new AssetMiddleware(next.Object, pipeline, logger.Object, builder.Object);
            var stream     = new MemoryStream();

            response.Setup(r => r.Body).Returns(stream);
            await middleware.InvokeAsync(context.Object, amo.Object);

            Assert.Equal("text/css", context.Object.Response.ContentType);
            Assert.Equal(cssContent.AsByteArray(), await stream.AsBytesAsync());
            Assert.Equal(0, response.Object.StatusCode);
        }
Пример #7
0

        
Пример #8
0
        public async Task AssetBuilder_NoMemoryCache()
        {
            byte[] cssContent = "*{color:red}".AsByteArray();

            var pipeline = new AssetPipeline();
            var options  = new WebOptimizerOptions()
            {
                EnableMemoryCache = false
            };
            var asset = new Mock <IAsset>().SetupAllProperties();

            asset.SetupGet(a => a.ContentType).Returns("text/css");
            asset.SetupGet(a => a.Route).Returns("/file.css");
            asset.Setup(a => a.GenerateCacheKey(It.IsAny <HttpContext>())).Returns("cachekey");
            asset.Setup(a => a.ExecuteAsync(It.IsAny <HttpContext>(), options))
            .Returns(Task.FromResult(cssContent));

            StringValues values;
            var          response = new Mock <HttpResponse>().SetupAllProperties();

            response.Setup(r => r.Headers.Keys).Returns(new string[] { });
            var context = new Mock <HttpContext>().SetupAllProperties();

            context.Setup(s => s.Request.Headers.TryGetValue("Accept-Encoding", out values)).Returns(false);
            context.Setup(c => c.Response).Returns(response.Object);
            context.Setup(c => c.Request.Path).Returns("/file.css");

            var next = new Mock <RequestDelegate>();
            var env  = new Mock <IHostingEnvironment>().SetupAllProperties();

            env.Setup(e => e.ContentRootPath).Returns(@"D:\Project\");

            object bytes;
            var    cache = new Mock <IMemoryCache>();

            cache.Setup(c => c.TryGetValue(It.IsAny <string>(), out bytes)).Throws <InvalidOperationException>();

            var store = new Mock <IAssetResponseStore>();

            var member = pipeline.GetType().GetField("_assets", BindingFlags.NonPublic | BindingFlags.Instance);

            member.SetValue(pipeline, new List <IAsset> {
                asset.Object
            });

            var amo = new Mock <IOptionsSnapshot <WebOptimizerOptions> >();

            amo.SetupGet(a => a.Value).Returns(options);

            var logger  = new Mock <ILogger <AssetBuilder> >();
            var builder = new AssetBuilder(cache.Object, store.Object, logger.Object, env.Object);

            var result = await builder.BuildAsync(asset.Object, context.Object, options).ConfigureAwait(false);

            Assert.Equal(cssContent, result.Body);
        }
Пример #9
0
        public void AddJsFiles_DefaultSettings_Success()
        {
            var pipeline = new AssetPipeline();
            var asset    = pipeline.MinifyJsFiles().First();

            Assert.Equal("/**/*.js", asset.Route);
            Assert.Equal("application/javascript; charset=UTF-8", asset.ContentType);
            Assert.True(1 == asset.SourceFiles.Count());
            Assert.True(1 == asset.Processors.Count);
        }
Пример #10
0
        public void AddCssBundle_DefaultSettings_Success()
        {
            var pipeline = new AssetPipeline();
            var asset    = pipeline.AddCssBundle("/foo.css", "file1.css", "file2.css");

            Assert.Equal("/foo.css", asset.Route);
            Assert.Equal("text/css; charset=UTF-8", asset.ContentType);
            Assert.Equal(2, asset.SourceFiles.Count());
            Assert.Equal(5, asset.Processors.Count);
        }
Пример #11
0
        public void AddZeroSourceFilesToBundle_Fail()
        {
            var env = new HostingEnvironment {
                EnvironmentName = "Development"
            };
            IAsset asset    = new Asset("/file.css", "text/css", new string[0]);
            var    pipeline = new AssetPipeline();

            Assert.Throws <ArgumentException>(() => pipeline.AddBundle(asset));
        }
        public void AddJsBundle_DefaultSettings_Success()
        {
            var pipeline = new AssetPipeline();
            var asset    = pipeline.AddJavaScriptBundle("/foo.js", "file1.js", "file2.js");

            Assert.Equal("/foo.js", asset.Route);
            Assert.Equal("text/javascript; charset=UTF-8", asset.ContentType);
            Assert.Equal(2, asset.SourceFiles.Count());
            Assert.Equal(4, asset.Processors.Count);
        }
Пример #13
0
        public void AddCssFiles_DefaultSettings_Success()
        {
            var pipeline = new AssetPipeline();
            var asset    = pipeline.MinifyCssFiles().First();

            Assert.Equal("/**/*.css", asset.Route);
            Assert.Equal("text/css; charset=UTF-8", asset.ContentType);
            Assert.True(1 == asset.SourceFiles.Count());
            Assert.True(2 == asset.Processors.Count);
        }
Пример #14
0
        public void AddHtmlBundle_CustomSettings_Success()
        {
            var settings = new HtmlSettings();
            var pipeline = new AssetPipeline();
            var asset    = pipeline.AddHtmlBundle("/foo.html", settings, "file1.css", "file2.css");

            Assert.Equal("/foo.html", asset.Route);
            Assert.Equal("text/html; charset=UTF-8", asset.ContentType);
            Assert.Equal(2, asset.SourceFiles.Count());
            Assert.Equal(3, asset.Processors.Count);
        }
Пример #15
0
        public void AddJsBundle_CustomSettings_Success()
        {
            var settings = new CodeSettings();
            var pipeline = new AssetPipeline();
            var asset    = pipeline.AddJavaScriptBundle("/foo.js", settings, "file1.js", "file2.js");

            Assert.Equal("/foo.js", asset.Route);
            Assert.Equal("application/javascript; charset=UTF-8", asset.ContentType);
            Assert.Equal(2, asset.SourceFiles.Count());
            Assert.Equal(3, asset.Processors.Count);
        }
Пример #16
0
        public void FromRoute_Globbing_WithItems_Success(string pattern, string path)
        {
            var pipeline = new AssetPipeline();

            pipeline.AddFiles("text/css", pattern).ForEach(x => x.UseContentRoot());

            Assert.True(pipeline.TryGetAssetFromRoute(path, out var a1));
            Assert.Equal($"/{path.TrimStart('/')}", a1.Route);
            Assert.Equal(1, a1.Items.Count);
            Assert.Contains(a1.Items, p => p.Key == "usecontentroot");
        }
        public void SetUp()
        {
            thePipeline = new AssetPipeline();
            var builder = new AssetPipelineBuilder(new FileSystem(), thePipeline, new PackageLog());

            builder.LoadFiles(new PackageAssetDirectory {
                Directory   = FileSystem.Combine("..", "..", "Jasmine", "TestPackage2"),
                PackageName = "Pak2"
            });

            theGraph = new SpecificationGraph(thePipeline);
        }
Пример #18
0
        public void AddSingeAsset_Success()
        {
            var env = new HostingEnvironment {
                EnvironmentName = "Development"
            };
            var asset    = new Asset("/route", "text/css", new[] { "file.css" });
            var pipeline = new AssetPipeline();

            pipeline.AddBundle(asset);

            Assert.Equal(1, pipeline.Assets.Count);
        }
Пример #19
0
        public async Task AssetBuilder_NoDiskCache()
        {
            byte[] cssContent = "*{color:red}".AsByteArray();

            var pipeline = new AssetPipeline();
            var options  = new WebOptimizerOptions()
            {
                EnableDiskCache = false
            };
            var asset = new Mock <IAsset>().SetupAllProperties();

            asset.SetupGet(a => a.ContentType).Returns("text/css");
            asset.SetupGet(a => a.Route).Returns("/file.css");
            asset.Setup(a => a.GenerateCacheKey(It.IsAny <HttpContext>())).Returns("cachekey");
            asset.Setup(a => a.ExecuteAsync(It.IsAny <HttpContext>(), options))
            .Returns(Task.FromResult(cssContent));

            StringValues values;
            var          response = new Mock <HttpResponse>().SetupAllProperties();

            response.Setup(r => r.Headers.Keys).Returns(new string[] { });
            var context = new Mock <HttpContext>().SetupAllProperties();

            context.Setup(s => s.Request.Headers.TryGetValue("Accept-Encoding", out values)).Returns(false);
            context.Setup(c => c.Response).Returns(response.Object);
            context.Setup(c => c.Request.Path).Returns("/file.css");

            var next = new Mock <RequestDelegate>();
            var env  = new Mock <IWebHostEnvironment>().SetupAllProperties();

            env.Setup(e => e.ContentRootPath).Returns(@"D:\Project\");

            var mco = new Mock <IOptions <MemoryCacheOptions> >();

            mco.SetupGet(o => o.Value).Returns(new MemoryCacheOptions());
            var cache = new MemoryCache(mco.Object);

            AssetResponse ar;
            var           store = new Mock <IAssetResponseStore>();

            store.Setup(s => s.TryGet(It.IsAny <string>(), It.IsAny <string>(), out ar)).Throws <InvalidOperationException>();

            pipeline._assets = new ConcurrentDictionary <string, IAsset>();
            pipeline._assets.TryAdd(asset.Object.Route, asset.Object);

            var logger  = new Mock <ILogger <AssetBuilder> >();
            var builder = new AssetBuilder(cache, store.Object, logger.Object, env.Object);

            var result = await builder.BuildAsync(asset.Object, context.Object, options).ConfigureAwait(false);

            Assert.Equal(cssContent, result.Body);
        }
Пример #20
0
        public void AddTwoAsset_Succes()
        {
            var env = new HostingEnvironment {
                EnvironmentName = "Development"
            };
            var asset1   = new Asset("/route1", "text/css", new[] { "file.css" });
            var asset2   = new Asset("/route2", "text/css", new[] { "file.css" });
            var pipeline = new AssetPipeline();

            pipeline.AddBundle(new[] { asset1, asset2 });

            Assert.Equal(2, pipeline.Assets.Count);
        }
Пример #21
0
        public void AddTwoSameRoutes_Throws()
        {
            var env = new HostingEnvironment {
                EnvironmentName = "Development"
            };
            var asset1   = new Asset("/route", "text/css", new[] { "file.css" });
            var asset2   = new Asset("/route", "text/css", new[] { "file.css" });
            var pipeline = new AssetPipeline();

            var ex = Assert.Throws <ArgumentException>(() => pipeline.AddBundle(new[] { asset1, asset2 }));

            Assert.Equal("route", ex.ParamName);
            Assert.Equal(1, pipeline.Assets.Count);
        }
Пример #22
0
        public void TryGetAssetFromRoute_Concurrency()
        {
            var pipeline = new AssetPipeline();

            pipeline._assets = new ConcurrentDictionary <string, IAsset>();

            pipeline._assets.TryAdd("/**/*.less", new Asset("/**/*.less", "text/css; charset=UFT-8", new [] { "**/*.less" }));
            pipeline._assets.TryAdd("/**/*.css", new Asset("/**/*.css", "text/css; charset=UFT-8", new [] { "**/*.css" }));

            Parallel.For(0, 100, iteration =>
            {
                pipeline.TryGetAssetFromRoute($"/some_file{iteration}.less", out var a1);
            });
        }
Пример #23
0
        public async Task AssetMiddleware_NoCache_EmptyResponse()
        {
            var pipeline = new AssetPipeline();
            var options  = new WebOptimizerOptions()
            {
                EnableCaching = false
            };
            var asset = new Mock <IAsset>().SetupAllProperties();

            asset.SetupGet(a => a.ContentType).Returns("text/css");
            asset.SetupGet(a => a.Route).Returns("/file.css");
            asset.Setup(a => a.ExecuteAsync(It.IsAny <HttpContext>(), options))
            .Returns(Task.FromResult(new byte[0]));

            StringValues values;
            var          context = new Mock <HttpContext>().SetupAllProperties();

            context.Setup(s => s.Request.Headers.TryGetValue("Accept-Encoding", out values))
            .Returns(false);

            context.Setup(c => c.Request.Path).Returns("/file.css");

            context.SetupGet(c => c.Response.Headers)
            .Returns(new HeaderDictionary());

            var next  = new Mock <RequestDelegate>();
            var env   = new HostingEnvironment();
            var cache = new Mock <IMemoryCache>();

            var member = pipeline.GetType().GetField("_assets", BindingFlags.NonPublic | BindingFlags.Instance);

            member.SetValue(pipeline, new List <IAsset> {
                asset.Object
            });

            var amo = new Mock <IOptionsSnapshot <WebOptimizerOptions> >();

            amo.SetupGet(a => a.Value).Returns(options);

            var logger     = new Mock <ILogger <AssetMiddleware> >();
            var builder    = new Mock <IAssetBuilder>();
            var middleware = new AssetMiddleware(next.Object, pipeline, logger.Object, builder.Object);

            var stream = new MemoryStream();

            await middleware.InvokeAsync(context.Object, amo.Object);

            next.Verify(n => n(context.Object), Times.Once);
        }
Пример #24
0
        public AssetServicesRegistry()
        {
            var pipeline = new AssetPipeline();

            SetServiceIfNone <IAssetPipeline>(pipeline);
            SetServiceIfNone <IAssetFileRegistration>(pipeline);

            SetServiceIfNone(new AssetGraph());
            SetServiceIfNone(new AssetLogsCache());

            SetServiceIfNone <IAssetCacheHeaders, AssetCacheHeaders>();

            SetServiceIfNone <IAssetTagWriter, AssetTagWriter>();

            SetServiceIfNone <ICombinationDeterminationService, CombinationDeterminationService>();

            SetServiceIfNone <IAssetCombinationCache, AssetCombinationCache>();
            SetServiceIfNone <IAssetDependencyFinder, AssetDependencyFinderCache>();
            SetServiceIfNone <IAssetTagPlanner, AssetTagPlanner>();
            SetServiceIfNone <IAssetTagBuilder, AssetTagBuilder>();
            SetServiceIfNone <IAssetRequirements, AssetRequirements>();

            SetServiceIfNone <IMissingAssetHandler, TraceOnlyMissingAssetHandler>();

            SetServiceIfNone <IAssetTagPlanCache, AssetTagPlanCache>();

            SetServiceIfNone <ITransformerPolicyLibrary, TransformerPolicyLibrary>();

            SetServiceIfNone <IContentPlanner, ContentPlanner>();
            SetServiceIfNone <IContentPlanCache, ContentPlanCache>();
            SetServiceIfNone <IContentPipeline, ContentPipeline>();

            SetServiceIfNone <IContentWriter, ContentWriter>();

            SetServiceIfNone <IETagGenerator <IEnumerable <AssetFile> >, AssetFileEtagGenerator>();

            SetServiceIfNone <IAssetContentCache, AssetContentCache>();
            SetServiceIfNone <IAssetFileChangeListener, AssetFileChangeListener>();
            SetServiceIfNone <IAssetFileWatcher, AssetFileWatcher>();

            FillType(typeof(IActivator), typeof(AssetPrecompilerActivator));
            FillType(typeof(IActivator), typeof(AssetGraphConfigurationActivator));
            FillType(typeof(IActivator), typeof(AssetPipelineBuilderActivator));
            FillType(typeof(IActivator), typeof(AssetDeclarationVerificationActivator));
            FillType(typeof(IActivator), typeof(MimetypeRegistrationActivator));
            FillType(typeof(IActivator), typeof(AssetCombinationBuildingActivator));
            FillType(typeof(IActivator), typeof(AssetPolicyActivator));
            FillType(typeof(IActivator), typeof(AssetFileWatchingActivator));
        }
Пример #25
0
        public void AddConcatinate_Assets_Success()
        {
            var env = new HostingEnvironment {
                EnvironmentName = "Development"
            };
            var asset1   = new Asset("/file1", "text/css", new[] { "file.css" });
            var asset2   = new Asset("/file2", "text/css", new[] { "file.css" });
            var pipeline = new AssetPipeline();
            var assets   = pipeline.AddBundle(new[] { asset1, asset2 });

            assets = assets.Concatenate();

            Assert.Equal(2, assets.Count());

            foreach (var asset in assets)
            {
                Assert.Equal(1, asset.Processors.Count);
                Assert.True(asset.Processors.First() is Concatenator);
            }
        }
        public void SetUp()
        {
            packageDirectory = ".".ToFullPath();
            _packages        = new List <IPackageInfo>();

            AssetFolderIs = AssetFolder.scripts;
            writeFile("a.js");
            writeFile("b.js");
            writeFile("folder1/c.js");
            writeFile("folder2/d.js");

            AssetFolderIs = AssetFolder.styles;
            writeFile("main.css");
            writeFile("page.css");
            writeFile("folder1/a.css");

            startPackage("pak1");
            AssetFolderIs = AssetFolder.scripts;
            writeFile("e.js");
            writeFile("f.js");

            startPackage("pak2");
            AssetFolderIs = AssetFolder.styles;
            writeFile("a.css");
            writeFile("b.css");
            writeFile("c.css");

            startPackage("pak3");
            AssetFolderIs = AssetFolder.scripts;
            writeFile("a.js");

            thePipeline = new AssetPipeline();
            var activator = new AssetPipelineBuilderActivator(thePipeline, new AssetLogsCache());

            theLog = new PackageLog();
            activator.Activate(_packages, theLog);

            Debug.WriteLine(theLog.FullTraceText());
        }
Пример #27
0
        public ContentPlan BuildPlan()
        {
            var library      = new TransformerPolicyLibrary(_policies);
            var combinations = new AssetCombinationCache();

            if (_combination != null)
            {
                combinations.StoreCombination(_combination.MimeType, _combination);
            }

            var pipeline = new AssetPipeline();

            _files.Each(f =>
            {
                var path = new AssetPath(AssetPipeline.Application, f.Name, f.Folder);
                pipeline.AddFile(path, f);
            });

            var planner = new ContentPlanner(combinations, pipeline, library);

            return(planner.BuildPlanFor(_name));
        }
Пример #28
0
        /// <summary>
        /// Adds WebOptimizer to the specified <see cref="IServiceCollection"/>.
        /// </summary>
        public static IServiceCollection AddWebOptimizer(this IServiceCollection services, Action <IAssetPipeline> assetPipeline)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (assetPipeline == null)
            {
                throw new ArgumentNullException(nameof(assetPipeline));
            }

            var pipeline = new AssetPipeline();

            assetPipeline(pipeline);

            services.TryAddSingleton <IMemoryCache, MemoryCache>();
            services.TryAddSingleton <IAssetPipeline>(factory => pipeline);
            services.TryAddSingleton <IAssetBuilder, AssetBuilder>();
            services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <WebOptimizerOptions>, WebOptimizerConfig>());

            return(services);
        }
Пример #29
0
        public void SetUp()
        {
            system = new FileSystem();
            system.DeleteDirectory(AppDirectory);
            system.DeleteDirectory(PackageDirectory);

            writeFiles();


            thePipeline = new AssetPipeline();
            theBuilder  = new AssetPipelineBuilder(new FileSystem(), thePipeline, new PackageLog());
            theBuilder.LoadFiles(new PackageAssetDirectory()
            {
                Directory   = AppDirectory,
                PackageName = AssetPipeline.Application
            });

            theBuilder.LoadFiles(new PackageAssetDirectory()
            {
                Directory   = PackageDirectory,
                PackageName = "pak1"
            });
        }
Пример #30
0
        /// <summary>
        /// Creates a tag helper for inlining content
        /// </summary>
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (string.IsNullOrEmpty(output.TagName))
            {
                // output.SuppressOutput() was called by another TagHelper before this one
                return;
            }

            if (!string.IsNullOrEmpty(Src))
            {
                output.Attributes.RemoveAll("inline");
                output.Attributes.RemoveAll("integrity");
                output.Attributes.RemoveAll("language");
                output.Attributes.RemoveAll("src");
                output.Attributes.RemoveAll("async");
                output.Attributes.RemoveAll("defer");

                string route   = AssetPipeline.NormalizeRoute(Src);
                string content = await GetFileContentAsync(route);

                output.Content.SetHtmlContent(content);
                output.TagMode = TagMode.StartTagAndEndTag;
            }
        }