示例#1
0
        public static string GetFilePath(Type type, string flag, string projectName = "")
        {
            var host = new TestHostingEnvironment();
            var proj = string.Empty;

            if (type.Module.Name == "ZKCloud")
            {
                proj = type.Assembly.GetName().Name + ".Test";
            }
            else
            {
                proj = type.Assembly.GetName().Name.Replace("Entities", "Services").Replace("zkcloudv11s", projectName);
            }

            var paths = type.Namespace.Replace(type.Assembly.GetName().Name, "")
                        .Split(".", StringSplitOptions.RemoveEmptyEntries);
            var filePath = $"{host.TestRootPath}\\{proj}".Replace("zkcloudv11s", projectName)
                           .Replace("Entities", "Services").Replace("test", "app");

            foreach (var item in paths)
            {
                filePath += "\\" + item.Replace("Entities", flag);
                DirectoryHelper.CreateIfNotExists(filePath);
            }

            return(filePath);
        }
示例#2
0
文件: CoreTest.cs 项目: adteven/alabo
        static CoreTest()
        {
            var testHostingEnvironment = new TestHostingEnvironment();
            var builder = new ConfigurationBuilder()
                          .SetBasePath(testHostingEnvironment.WebRootPath).AddJsonFile("web.json", true, true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();
            Configuration.ConfigurationRuntimePath(testHostingEnvironment.WebRootPath);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(services =>
                                                                              new HttpContextAccessor
            {
                HttpContext = new DefaultHttpContext
                {
                    RequestServices = services
                }
            });

            //   services.AddTasks();
            services.AddMvc();
            // 项目底层配置服务
            services.AddAppServcie(Configuration);
            //添加Mvc服务
            services.AddMvc(options =>
            {
                //options.Filters.Add( new AutoValidateAntiforgeryTokenAttribute() );
                options.Filters.Add(new ExceptionHandlerAttribute());
            }
                            ).AddControllersAsServices();

            //添加NLog日志操作
            services.AddNLog();

            //添加事件总线服务
            services.AddEventBus();

            //注册XSRF令牌服务
            services.AddXsrfToken();

            //添加工作单元
            var config   = Configuration.GetConnectionString("ConnectionString");
            var database = RuntimeContext.GetTenantMongodbDataBase();

            config = config.Replace(RuntimeContext.Current.WebsiteConfig.MongoDbConnection.Database, database);
            services.AddUnitOfWork <IUnitOfWork, SqlServerUnitOfWork>(config);

            services.AddTestService <ITest, ITestBase>();
            // Api 接口相关服务
            services.AddApiService();
            // 添加支付方式等,第三方注入
            services.AddApiStoreService();

            services.AddUtil();
        }
            private void ShouldReturnTrueForAllEnvironments(string environmentName)
            {
                var hostingEnvironment = new TestHostingEnvironment
                {
                    EnvironmentName = environmentName
                };
                var options = new SeoOptions();

                DefaultOptions.Configure(options, hostingEnvironment);

                options.RobotsTxt.AddSitemapUrl.Should().BeTrue();
            }
示例#4
0
        public void CreateTest(Type type)
        {
            var moduleAttribute = Resolve <ITaskModuleConfigService>().GetModuleAttribute(type);

            if (moduleAttribute == null)
            {
                throw new ValidException("请定义模块特性");
            }

            var host        = new TestHostingEnvironment();
            var testBuilder = new StringBuilder();
            var proj        = string.Empty;

            if (type.Module.Name == "ZKCloud")
            {
                proj = type.Assembly.GetName().Name + ".Test";
            }
            else
            {
                proj = type.Assembly.GetName().Name.Replace(".App.", ".Test.");
            }

            var paths = type.Namespace.Replace(type.Assembly.GetName().Name, "")
                        .Split(".", StringSplitOptions.RemoveEmptyEntries);
            var filePath = $"{host.TestRootPath}\\{proj}";

            foreach (var item in paths)
            {
                filePath += "\\" + item;
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
            }

            var fileName = $"{filePath}\\{type.Name}Tests.cs";

            if (!File.Exists(fileName))
            {
                var templatePath = host.TestRootPath + "/Alabo.Test/Generation/Template/ShareTestTemplate.txt";
                var template     = FileHelper.Read(templatePath);

                var testFullName = type.FullName;
                template = template.Replace("[[TestFullName]]",
                                            type.FullName.Replace("App.", "Test.").Replace($".{type.Name}", ""));
                template = template.Replace("[[ClassName]]", $"{type.Name}Tests");
                template = template.Replace("[[ModuleFullName]]", type.FullName);

                FileHelper.Write(fileName, template);
            }
        } /*end*/
            private void ShouldAllowSiteWideAccessInProduction(string environmentName, bool expected)
            {
                var hostingEnvironment = new TestHostingEnvironment
                {
                    EnvironmentName = environmentName
                };
                var options = new SeoOptions();

                DefaultOptions.Configure(options, hostingEnvironment);

                UserAgentRecord userAgentRecord = options.RobotsTxt.UserAgentRecords.Single();

                userAgentRecord.DisallowAll.Should().Be(expected);
            }
示例#6
0
        public void StartSingleServieCode(Type type, bool isBase = false, bool isZkcloud = false)
        {
            // type = typeof(IAutoReportService);

            // 参考Alabo.Linq.Dynamic.DynamicService.ResolveMethod
            var instanse     = DynamicService.Resolve(type.Name);
            var instanseType = type;

            if (instanse == null)
            {
                instanseType = instanseType.GetType();
            }

            var host        = new TestHostingEnvironment();
            var testBuilder = new StringBuilder();
            var proj        = string.Empty;

            if (type.Module.Name == "ZKCloud")
            {
                proj = type.Assembly.GetName().Name + ".Test";
            }

            proj = type.Assembly.GetName().Name.Replace(".App.", ".Test.");

            var paths = type.Namespace.Replace(type.Assembly.GetName().Name, "")
                        .Split(".", StringSplitOptions.RemoveEmptyEntries);
            var filePath = $"{host.TestRootPath}\\{proj}";

            if (isZkcloud)
            {
                filePath += ".Test";
            }

            foreach (var item in paths)
            {
                filePath += "\\" + item;
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
            }

            var fileName = $"{filePath}\\{type.Name}Tests.cs";

            if (isBase)
            {
                fileName = $"{filePath}\\{type.Name}BaseTests.cs";
            }

            var methods = instanseType.GetMethods(); // 当前服务所有的方法

            // 底层继承的方法不显示

            methods = methods.Where(r => r.Module.Name.Contains("ZKCloud")).ToArray();
            if (isZkcloud)
            {
                methods = methods.Where(r => r.Module.Name == "Alabo.dll").ToArray();
            }
            else
            {
                methods = methods.Where(r => r.Module.Name != "Alabo.dll").ToArray();
            }

            // methods = methods.Where(r => r.Name == "AddOrUpdate").ToArray();
            var namespaceList = new List <string>();

            if (File.Exists(fileName))
            {
                using (var stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    var text   = string.Empty;
                    var reader = new StreamReader(stream);
                    text = reader.ReadToEnd();
                    //增量模式
                    var isAppend = false; // 是否增量增加

                    // 额外方法处理
                    if (isBase)
                    {
                        var commonTest = TemplateServiceTest.CreateCommonTest(text, type.Name);
                        if (!commonTest.IsNullOrEmpty())
                        {
                            isAppend = true;
                            testBuilder.Append(commonTest);
                        }
                    }
                    else
                    {
                        foreach (var method in methods)
                        {
                            if (HanderMethod(method) == null)
                            {
                                continue;
                            }

                            var methodParameters = method.GetParameters(); // 方法参数
                            var name             = method.Name + GetTestNameFromParameterInfo(methodParameters, out var param);

                            if (text.IndexOf($@"[TestMethod(""{name}"")]", StringComparison.OrdinalIgnoreCase) != -1)
                            {
                                continue;
                            }

                            //生成测试方法
                            testBuilder.Append(CreateMethodTest(method, type));
                            isAppend = true;
                        }
                    }

                    testBuilder.AppendLine("/*end*/");
                    text = text.Replace("/*end*/", testBuilder.ToString());

                    if (isAppend)
                    {
                        using (var writer = new StreamWriter(stream))
                        {
                            stream.Position = 0;
                            writer.Write(text);
                        }
                    }
                }

                return;
            }

            #region 命名空间处理

            testBuilder.AppendLine("using Xunit;");
            testBuilder.AppendLine($"using {type.Namespace};");
            testBuilder.AppendLine("using Alabo.Test.Core;");
            testBuilder.AppendLine("using System.Linq;");
            testBuilder.AppendLine(
                "using System;using Alabo.Domains.Repositories.EFCore;using Alabo.Domains.Repositories.Model;");
            testBuilder.AppendLine("using System.Collections.Generic;");
            testBuilder.AppendLine("using Alabo.Test.Base.Core.Model;");

            if (!isBase)
            {
                foreach (var method in methods)
                {
                    if (HanderMethod(method) == null)
                    {
                        continue;
                    }

                    var methodParameters = method.GetParameters(); // 方法参数
                    var param            = string.Empty;
                    foreach (var item in methodParameters)
                    {
                        if (testBuilder.ToString()
                            .IndexOf(item.ParameterType.Namespace, StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            testBuilder.AppendLine($"using {item.ParameterType.Namespace};");
                        }
                    }
                }
            }

            testBuilder.AppendLine();
            testBuilder.AppendLine($"namespace {type.Namespace.Replace(".App.", ".Test.")} {{");
            testBuilder.AppendLine("using User = Alabo.App.Core.User.Domain.Entities.User;");
            testBuilder.AppendLine("using Product = Alabo.App.Shop.Product.Domain.Entities.Product;");
            testBuilder.AppendLine("using Order = Alabo.App.Shop.Order.Domain.Entities.Order;");
            testBuilder.AppendLine("using Store = Alabo.App.Shop.Store.Domain.Store;");
            testBuilder.AppendLine("");
            testBuilder.AppendLine("using UserType = App.Core.UserType.Domain.Entities.UserType;");

            #endregion 命名空间处理

            if (isBase)
            {
                testBuilder.AppendLine($"\tpublic class {type.Name}BaseTests : CoreTest {{");
            }

            testBuilder.AppendLine($"\tpublic class {type.Name}Tests : CoreTest {{");

            if (!isBase)
            {
                foreach (var method in methods)
                {
                    testBuilder.Append(CreateMethodTest(method, type));
                }
            }

            testBuilder.AppendLine("/*end*/");
            testBuilder.AppendLine("\t}");
            testBuilder.AppendLine("}");
            //创建文件

            using (var stream = File.Create(fileName))
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(testBuilder);
                }
            }
        }