[DONT MERGE]

vnext
Paul Schneider 4 years ago
parent b4698d2eda
commit f7555b6afb
8 changed files with 204 additions and 132 deletions

@ -31,26 +31,22 @@ namespace test
[Trait("regres", "no")] [Trait("regres", "no")]
public class BatchTests: BaseTestContext, IClassFixture<ServerSideFixture>, IDisposable public class BatchTests: BaseTestContext, IClassFixture<ServerSideFixture>, IDisposable
{ {
readonly ApplicationDbContext _dbContext;
ServerSideFixture _fixture; ServerSideFixture _fixture;
public BatchTests(ITestOutputHelper output, ServerSideFixture fixture) : base (output, fixture) public BatchTests(ITestOutputHelper output, ServerSideFixture fixture) : base (output, fixture)
{ {
_dbContext = fixture.DbContext;
_fixture = fixture; _fixture = fixture;
if (!_fixture.DbCreated)
_fixture.CreateTestDb();
} }
[Fact] [Fact]
public void GitClone() public void GitClone()
{ {
var firstProject = _dbContext.Project.Include(p=>p.Repository).FirstOrDefault(); _serverFixture.EnsureTestDb();
var firstProject = _fixture.DbContext.Project.Include(p=>p.Repository).FirstOrDefault();
Assert.NotNull (firstProject); Assert.NotNull (firstProject);
var di = new DirectoryInfo(_serverFixture.SiteSetup.GitRepository); var di = new DirectoryInfo(_serverFixture.SiteSetup.GitRepository);
if (!di.Exists) di.Create(); if (!di.Exists) di.Create();
var clone = new GitClone(_serverFixture.SiteSetup.GitRepository); var clone = new GitClone(_serverFixture.SiteSetup.GitRepository);
clone.Launch(firstProject); clone.Launch(firstProject);
gitRepo = di.FullName; gitRepo = di.FullName;
@ -86,12 +82,12 @@ namespace test
[Fact] [Fact]
void HaveHost() void HaveHost()
{ {
beforeCompileContext = CreateYavscCompilationContext();
} }
[Fact] [Fact]
public void AConfigurationRoot() public void EnsureConfigurationRoot()
{ {
var builder = new ConfigurationBuilder(); var builder = new ConfigurationBuilder();
builder.AddJsonFile( "appsettings.json", false); builder.AddJsonFile( "appsettings.json", false);
@ -149,12 +145,11 @@ namespace test
{ {
options.ResourcesPath = "Resources"; options.ResourcesPath = "Resources";
}); });
var connectionString = configuration["ConnectionStrings:Default"]; AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", Startup.Testing.ConnectionStrings.Default);
AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", connectionString);
serviceCollection.AddEntityFramework() serviceCollection.AddEntityFramework()
.AddNpgsql() .AddNpgsql()
.AddDbContext<ApplicationDbContext>( .AddDbContext<ApplicationDbContext>(
db => db.UseNpgsql(connectionString) db => db.UseNpgsql(Startup.Testing.ConnectionStrings.Default)
); );
provider = serviceCollection.BuildServiceProvider(); provider = serviceCollection.BuildServiceProvider();
} }
@ -164,12 +159,11 @@ namespace test
public void ARequestAppDelegate() public void ARequestAppDelegate()
{ {
var services = new ServiceCollection(); var services = new ServiceCollection();
services.AddTransient<IRuntimeEnvironment>( services.AddTransient<IRuntimeEnvironment>(
svs => PlatformServices.Default.Runtime svs => PlatformServices.Default.Runtime
); );
HaveHost(); beforeCompileContext = CreateYavscCompilationContext();
var prjDir = this.beforeCompileContext.ProjectContext.ProjectDirectory; var prjDir = this.beforeCompileContext.ProjectContext.ProjectDirectory;
ConfigureServices(services, prjDir, out configurationRoot, out serviceProvider); ConfigureServices(services, prjDir, out configurationRoot, out serviceProvider);
@ -178,6 +172,7 @@ namespace test
} }
[Fact] [Fact]
public void InitApplicationBuilder() public void InitApplicationBuilder()
{ {
@ -203,9 +198,7 @@ namespace test
{ {
Directory.Delete(Path.Combine(gitRepo,"yavsc"), true); Directory.Delete(Path.Combine(gitRepo,"yavsc"), true);
} }
if (_fixture.DbCreated) _fixture.DropTestDb();
_fixture.DropTestDb();
} }
} }
} }

@ -15,10 +15,18 @@ namespace test.Mandatory
{ {
this.output = output; this.output = output;
_serverFixture = serverFixture; _serverFixture = serverFixture;
if (_serverFixture.DbCreated) try {
_serverFixture.DropTestDb();
output.WriteLine($"Startup.DbSettings.Testing is {Startup.DbSettings.Testing}"); = new Microsoft.Data.Entity.Infrastructure.DatabaseFacade(_serverFixture.DbContext.Database);
_serverFixture.DropTestDb();
}
catch (Exception)
{
output.WriteLine("db not dropped");
}
output.WriteLine($"Startup.Testing.ConnectionStrings.DatabaseCtor is {Startup.Testing.ConnectionStrings.DatabaseCtor}");
} }
/// <summary> /// <summary>
@ -28,14 +36,14 @@ namespace test.Mandatory
[Fact] [Fact]
public void InstallFromScratchUsingPoweredNpgsqlUser() public void InstallFromScratchUsingPoweredNpgsqlUser()
{ {
_serverFixture.CreateTestDb();
_serverFixture.EnsureTestDb();
_serverFixture.UpgradeDb(); _serverFixture.UpgradeDb();
} }
public void Dispose() public void Dispose()
{ {
if (_serverFixture.DbCreated) _serverFixture.DropTestDb();
_serverFixture.DropTestDb();
} }
} }

@ -4,10 +4,13 @@
// */ // */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
using Yavsc.Authentication; using Yavsc.Authentication;
@ -22,6 +25,7 @@ namespace test
public Remoting(ServerSideFixture serverFixture, ITestOutputHelper output) public Remoting(ServerSideFixture serverFixture, ITestOutputHelper output)
: base(output, serverFixture) : base(output, serverFixture)
{ {
} }
[Theory] [Theory]
@ -42,10 +46,14 @@ namespace test
{ {
var oauthor = new OAuthenticator(clientId, clientSecret, scope, var oauthor = new OAuthenticator(clientId, clientSecret, scope,
new Uri(authorizeUrl), new Uri(redirectUrl), new Uri(accessTokenUrl)); new Uri(authorizeUrl), new Uri(redirectUrl), new Uri(accessTokenUrl));
var query = new Dictionary<string, string>(); var query = new Dictionary<string, string>
query[Parameters.Username] = login; {
query[Parameters.Password] = pass; [Parameters.Username] = Startup.Testing.ValidCreds[0].UserName,
query[Parameters.GrantType] = GrantTypes.Password; [Parameters.Password] = Startup.Testing.ValidCreds[0].Password,
[Parameters.GrantType] = GrantTypes.Password
};
EnsureWeb();
var result = await oauthor.RequestAccessTokenAsync(query); var result = await oauthor.RequestAccessTokenAsync(query);
Console.WriteLine(">> Got an output"); Console.WriteLine(">> Got an output");
Console.WriteLine(Parameters.AccessToken + ": " + result[Parameters.AccessToken]); Console.WriteLine(Parameters.AccessToken + ": " + result[Parameters.AccessToken]);
@ -68,49 +76,46 @@ namespace test
throw; throw;
} }
} }
public static string GetPassword() internal static void EnsureWeb()
{ {
var pwd = new StringBuilder(); DirectoryInfo di = new DirectoryInfo("../Yavsc");
while (true) Environment.CurrentDirectory = di.FullName;
{ var host = new WebHostBuilder();
var len = pwd.ToString().Length;
ConsoleKeyInfo i = Console.ReadKey(true); var hostengine = host
if (i.Key == ConsoleKey.Enter)
{ .UseEnvironment("Development")
break;
} .UseServer("web")
else if (i.Key == ConsoleKey.Backspace) .UseStartup<Yavsc.Startup>()
{ .Build();
if (pwd.Length > 0) // hostengine.ApplicationServices
{ var startup = hostengine.Start();
pwd.Remove(len - 1, 1);
Console.Write("\b \b");
}
}
else
{
pwd.Append(i.KeyChar);
Console.Write("*");
}
}
return pwd.ToString();
} }
public static IEnumerable<object[]> GetLoginIntentData(int numTests) public static IEnumerable<object[]> GetLoginIntentData(int numTests)
{ {
var allData = new List<object[]>(); var allData = new List<object[]>();
Console.WriteLine($"Please, enter {numTests}:");
for (int iTest=0; iTest<numTests; iTest++) for (int iTest=0; iTest < numTests && iTest < Startup.Testing.ValidCreds.Length; iTest++)
{
var login = Startup.Testing.ValidCreds[iTest].UserName;
var pass = Startup.Testing.ValidCreds[iTest].Password;
allData.Add(new object[] { ServerSideFixture.ApiKey, "blouh", "profile",
"http://localhost:5000/authorize", "http://localhost:5000/oauth/success",
"http://localhost:5000/token",login, pass});
}
var valid = allData.Count;
for (int iTest=0; iTest + valid < numTests && iTest < Startup.Testing.InvalidCreds.Length; iTest++)
{ {
Console.Write("Please, enter a login:"); var login = Startup.Testing.InvalidCreds[iTest].UserName;
var login = Console.ReadLine(); var pass = Startup.Testing.InvalidCreds[iTest].Password;
Console.Write("Please, enter a pass:");
var pass = GetPassword();
allData.Add(new object[] { ServerSideFixture.ApiKey, "blouh", "profile", allData.Add(new object[] { ServerSideFixture.ApiKey, "blouh", "profile",
"http://localhost:5000/authorize", "http://localhost:5000/oauth/success", "http://localhost:5000/authorize", "http://localhost:5000/oauth/success",
"http://localhost:5000/token",login, pass }); "http://localhost:5000/token",login, 0 });
} }
return allData.Take(numTests); return allData.Take(numTests);

@ -10,11 +10,15 @@ using Yavsc;
using Yavsc.Models; using Yavsc.Models;
using Xunit; using Xunit;
using Npgsql; using Npgsql;
using test.Settings;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata.Conventions;
namespace test namespace test
{ {
[Trait("regres", "no")] [Trait("regres", "no")]
public class ServerSideFixture : IDisposable { public class ServerSideFixture : IDisposable
{
SiteSettings _siteSetup; SiteSettings _siteSetup;
ILogger _logger; ILogger _logger;
IApplication _app; IApplication _app;
@ -22,9 +26,9 @@ namespace test
ILoggerFactory _loggerFactory; ILoggerFactory _loggerFactory;
IEmailSender _mailSender; IEmailSender _mailSender;
public static string ApiKey => "53f4d5da-93a9-4584-82f9-b8fdf243b002" ; public static string ApiKey => "53f4d5da-93a9-4584-82f9-b8fdf243b002";
public ApplicationDbContext DbContext { get; private set; } public ApplicationDbContext DbContext { get; private set; }
public SiteSettings SiteSetup public SiteSettings SiteSetup
{ {
get get
@ -38,6 +42,12 @@ namespace test
} }
} }
/// <summary>
/// initialized by Init
/// </summary>
/// <value></value>
public static object TestingSetup { get; private set; }
public IEmailSender MailSender public IEmailSender MailSender
{ {
get get
@ -64,10 +74,12 @@ namespace test
} }
} }
internal void UpgradeDb() internal void UpgradeDb()
{ {
Microsoft.Data.Entity.Commands.Program.Main( Microsoft.Data.Entity.Commands.Program.Main(
new string [] { "database", "update" }); new string[] { "database", "update" });
} }
public ILogger Logger public ILogger Logger
@ -82,95 +94,107 @@ namespace test
_logger = value; _logger = value;
} }
} }
public bool DbCreated { get; private set; } bool dbCreated;
private WebHostBuilder host;
private IHostingEngine hostengnine;
// //
public ServerSideFixture() public ServerSideFixture()
{ {
InitTestHost(); host = new WebHostBuilder();
Logger.LogInformation("ServerSideFixture created.");
}
[Fact] hostengnine = host
void InitTestHost()
{
var host = new WebHostBuilder();
var hostengnine = host
.UseEnvironment("Development") .UseEnvironment("Development")
.UseServer("test") .UseServer("test")
.UseStartup<test.Startup>() .UseStartup<test.Startup>()
.Build(); .Build();
App = hostengnine.Start(); App = hostengnine.Start();
// hostengnine.ApplicationServices
_mailer = App.Services.GetService(typeof(EMailer)) as EMailer; _mailer = App.Services.GetService(typeof(EMailer)) as EMailer;
_loggerFactory = App.Services.GetService(typeof(ILoggerFactory)) as ILoggerFactory; _loggerFactory = App.Services.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
Logger = _loggerFactory.CreateLogger<ServerSideFixture> ();
var siteSetup = App.Services.GetService(typeof(IOptions<SiteSettings>)) as IOptions<SiteSettings>; var siteSetup = App.Services.GetService(typeof(IOptions<SiteSettings>)) as IOptions<SiteSettings>;
SiteSetup = siteSetup.Value; var testingSetup = App.Services.GetService(typeof(IOptions<Testing>)) as IOptions<Testing>;
MailSender = App.Services.GetService(typeof(IEmailSender)) as IEmailSender; MailSender = App.Services.GetService(typeof(IEmailSender)) as IEmailSender;
DbContext = App.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
SiteSetup = siteSetup.Value;
TestingSetup = testingSetup.Value;
var builder = new DbConnectionStringBuilder();
builder.ConnectionString = Startup.DbSettings.Testing;
Logger.LogInformation("testing database:" +builder["Database"]);
TestingDatabase = (string) builder["Database"];
CheckDbExistence(); Logger = _loggerFactory.CreateLogger<ServerSideFixture>();
if (!DbCreated)
CreateTestDb();
DbContext = App.Services.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
var builder = new DbConnectionStringBuilder
{
ConnectionString = Startup.Testing.ConnectionStrings.Default
};
ConventionSet conventions = new ConventionSet();
modelBuilder = new ModelBuilder(conventions);
ApplicationDbContext context = new ApplicationDbContext();
TestingDatabase = (string)builder["Database"];
Logger.LogInformation("ServerSideFixture created.");
} }
[Fact]
public void InitTestHost()
{
EnsureTestDb();
}
private ModelBuilder modelBuilder;
public string TestingDatabase { get; private set; } public string TestingDatabase { get; private set; }
public void CheckDbExistence() public void CheckDbExistence()
{ {
using ( using (
NpgsqlConnection cx = new NpgsqlConnection(Startup.DbSettings.DatabaseCtor)) NpgsqlConnection cx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.DatabaseCtor))
{ {
cx.Open(); cx.Open();
var command = cx.CreateCommand(); var command = cx.CreateCommand();
command.CommandText = $"SELECT 1 FROM pg_database WHERE datname='{TestingDatabase}';"; command.CommandText = $"SELECT 1 FROM pg_database WHERE datname='{TestingDatabase}';";
DbCreated = (command.ExecuteScalar()!=null); dbCreated = (command.ExecuteScalar()!=null);
_logger.LogInformation($"DbCreated:{dbCreated}");
_logger.LogInformation($"DbCreated:{DbCreated}");
cx.Close(); cx.Close();
} }
} }
public void CreateTestDb()
public bool EnsureTestDb()
{ {
if (!DbCreated) CheckDbExistence();
using ( if (!dbCreated)
NpgsqlConnection cx = new NpgsqlConnection(Startup.DbSettings.DatabaseCtor))
{ {
cx.Open(); using (NpgsqlConnection cx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.DatabaseCtor))
var command = cx.CreateCommand(); {
command.CommandText = $"create database \"{TestingDatabase}\";";
command.ExecuteNonQuery(); cx.Open();
var command = cx.CreateCommand();
_logger.LogInformation($"database created."); using (NpgsqlConnection ownercx = new NpgsqlConnection(Startup.Testing.ConnectionStrings.Default))
cx.Close(); command.CommandText = $"create database '{TestingDatabase}' OWNER = '{ownercx.UserName}';";
command.ExecuteNonQuery();
}
dbCreated = DbContext.Database.EnsureCreated();
} }
DbCreated=true; return dbCreated;
} }
public void DropTestDb() public void DropTestDb()
{ {
if (DbCreated) if (dbCreated)
using ( DbContext.Database.EnsureDeleted();
NpgsqlConnection cx = new NpgsqlConnection(Startup.DbSettings.DatabaseCtor)) dbCreated = false;
{
cx.Open();
var command = cx.CreateCommand();
command.CommandText = $"drop database \"{TestingDatabase}\"";
command.ExecuteNonQuery();
_logger.LogInformation($"database dropped");
cx.Close();
}
DbCreated=false;
} }
public void Dispose() public void Dispose()

@ -4,6 +4,5 @@ namespace test.Settings
{ {
public string DatabaseCtor { get; set; } public string DatabaseCtor { get; set; }
public string Default { get; set; } public string Default { get; set; }
public string Testing { get; set; }
} }
} }

@ -0,0 +1,22 @@
namespace test.Settings
{
public class PasswordCreds
{
public string UserName { get; set; }
public string Password { get; set; }
}
public class Testing
{
public DbConnectionSettings ConnectionStrings { get; set; }
public PasswordCreds[] ValidCreds
{
get; set;
}
public PasswordCreds[] InvalidCreds
{
get; set;
}
}
}

@ -13,7 +13,6 @@ using Yavsc.Services;
using Microsoft.Data.Entity; using Microsoft.Data.Entity;
using Microsoft.Extensions.WebEncoders; using Microsoft.Extensions.WebEncoders;
using test.Settings; using test.Settings;
namespace test namespace test
{ {
public class Startup public class Startup
@ -22,7 +21,7 @@ namespace test
public static IConfiguration Configuration { get; set; } public static IConfiguration Configuration { get; set; }
public static string HostingFullName { get; private set; } public static string HostingFullName { get; private set; }
public static DbConnectionSettings DbSettings { get; private set; } public static Testing Testing { get; private set; }
ILogger logger; ILogger logger;
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
@ -55,6 +54,8 @@ namespace test
services.Configure<SmtpSettings>(smtpSettingsconf); services.Configure<SmtpSettings>(smtpSettingsconf);
var dbSettingsconf = Configuration.GetSection("ConnectionStrings"); var dbSettingsconf = Configuration.GetSection("ConnectionStrings");
services.Configure<DbConnectionSettings>(dbSettingsconf); services.Configure<DbConnectionSettings>(dbSettingsconf);
var testingconf = Configuration.GetSection("Testing");
services.Configure<Testing>(testingconf);
services.AddInstance(typeof(ILoggerFactory), new LoggerFactory()); services.AddInstance(typeof(ILoggerFactory), new LoggerFactory());
services.AddTransient(typeof(IEmailSender), typeof(MailSender)); services.AddTransient(typeof(IEmailSender), typeof(MailSender));
@ -70,7 +71,7 @@ namespace test
services.AddEntityFramework() services.AddEntityFramework()
.AddNpgsql() .AddNpgsql()
.AddDbContext<ApplicationDbContext>( .AddDbContext<ApplicationDbContext>(
db => db.UseNpgsql(Startup.DbSettings.Default) db => db.UseNpgsql(Testing.ConnectionStrings.Default)
); );
services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>(); services.AddTransient<Microsoft.Extensions.WebEncoders.UrlEncoder, UrlEncoder>();
@ -78,19 +79,19 @@ namespace test
} }
public void Configure (IApplicationBuilder app, IHostingEnvironment env, public void Configure (IApplicationBuilder app, IHostingEnvironment env,
IOptions<SiteSettings> siteSettings, IOptions<Testing> testingSettings,
IOptions<DbConnectionSettings> cxOptions,
ILoggerFactory loggerFactory) ILoggerFactory loggerFactory)
{ {
loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug(); loggerFactory.AddDebug();
logger = loggerFactory.CreateLogger<Startup>(); logger = loggerFactory.CreateLogger<Startup>();
logger.LogInformation(env.EnvironmentName); logger.LogInformation(env.EnvironmentName);
Testing = testingSettings.Value;
DbSettings = cxOptions.Value; if (Testing.ConnectionStrings==null)
logger.LogInformation($"default db : {DbSettings.Default}"); logger.LogInformation($" Testing.ConnectionStrings is null : ");
logger.LogInformation($"test db : {DbSettings.Testing}"); else {
AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", DbSettings.Default); AppDomain.CurrentDomain.SetData("YAVSC_DB_CONNECTION", Testing.ConnectionStrings.Default);
}
var authConf = Configuration.GetSection("Authentication").GetSection("Yavsc"); var authConf = Configuration.GetSection("Authentication").GetSection("Yavsc");
var clientId = authConf.GetSection("ClientId").Value; var clientId = authConf.GetSection("ClientId").Value;

@ -38,9 +38,29 @@
"Microsoft": "Warning" "Microsoft": "Warning"
} }
}, },
"ConnectionStrings": { "Testing": {
"Default": "Server=[Default NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];", "ConnectionStrings": {
"DatabaseCtor": "Server=[Ctor NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];", "Default": "Server=lame-NpgsqlHostName;Port=5432;Database=lame-DataBase;Username=lame-Username;Password=lame-dbPassword;",
"Testing": "Server=[Testing NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];" "DatabaseCtor": "Server=lame-NpgsqlHostName;Port=5432;Database=lame-ctor-DataBase;Username=lame-ctor-Username;Password=lame-ctordbPassword;"
} },
"ValidCreds": [
{
"UserName": "lame-user",
"Password": "lame-password"
}
],
"InvalidCreds": [
{
"UserName": "lame-fakeuser",
"Password": "lame-fakepassword"
}
]
},
"DataProtection": {
"Keys": {
"Dir": "DataProtection-Keys"
},
"RSAParamFile": "ls ",
"ExpiresInHours": 168
}
} }

Loading…