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

@ -15,10 +15,18 @@ namespace test.Mandatory
{
this.output = output;
_serverFixture = serverFixture;
if (_serverFixture.DbCreated)
_serverFixture.DropTestDb();
output.WriteLine($"Startup.DbSettings.Testing is {Startup.DbSettings.Testing}");
try {
= 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>
@ -28,14 +36,14 @@ namespace test.Mandatory
[Fact]
public void InstallFromScratchUsingPoweredNpgsqlUser()
{
_serverFixture.CreateTestDb();
_serverFixture.EnsureTestDb();
_serverFixture.UpgradeDb();
}
public void Dispose()
{
if (_serverFixture.DbCreated)
_serverFixture.DropTestDb();
_serverFixture.DropTestDb();
}
}

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

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

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

@ -38,9 +38,29 @@
"Microsoft": "Warning"
}
},
"ConnectionStrings": {
"Default": "Server=[Default NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];",
"DatabaseCtor": "Server=[Ctor NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];",
"Testing": "Server=[Testing NpgsqlHostName];Port=5432;Database=[DataBase];Username=[Username];Password=[Password];"
}
"Testing": {
"ConnectionStrings": {
"Default": "Server=lame-NpgsqlHostName;Port=5432;Database=lame-DataBase;Username=lame-Username;Password=lame-dbPassword;",
"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…