test all of it

This commit is contained in:
Paul Schneider 2026-07-05 18:16:52 +01:00
commit 39ff100eab
8 changed files with 168 additions and 46 deletions

View file

@ -19,5 +19,6 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="unleash.client" Version="6.2.1" /> <PackageReference Include="unleash.client" Version="6.2.1" />
<Reference Include="System.Net.Http" Version="4.0.0.0" /> <Reference Include="System.Net.Http" Version="4.0.0.0" />
<ProjectReference Include="..\isn.abstract\isn.abstract.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -61,13 +61,26 @@ namespace isnd
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
}); });
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var useInMemoryDatabase = Configuration.GetValue<bool>("UseInMemoryDatabase") ||
string.IsNullOrWhiteSpace(connectionString) ||
connectionString.Contains("<", StringComparison.Ordinal);
services.Configure<SmtpSettings>(smtpSettingsconf) services.Configure<SmtpSettings>(smtpSettingsconf)
.Configure<IsndSettings>(isndSettingsconf) .Configure<IsndSettings>(isndSettingsconf)
.Configure<AdminStartupList>(adminStartupListConf) .Configure<AdminStartupList>(adminStartupListConf)
.Configure<MigrationsEndPointOptions>(o => o.Path = "~/migrate") .Configure<MigrationsEndPointOptions>(o => o.Path = "~/migrate")
.AddDbContext<ApplicationDbContext>(options => .AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql( {
Configuration.GetConnectionString("DefaultConnection"))) if (useInMemoryDatabase)
{
options.UseInMemoryDatabase("isnd-tests");
}
else
{
options.UseNpgsql(connectionString);
}
})
.AddIdentity<ApplicationUser, IdentityRole>() .AddIdentity<ApplicationUser, IdentityRole>()
.AddRoles<IdentityRole>() .AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>() .AddEntityFrameworkStores<ApplicationDbContext>()

View file

@ -3,15 +3,8 @@
foreach (string leashed in new string[] { "pkg-push", "pkg-get", foreach (string leashed in new string[] { "pkg-push", "pkg-get",
"pkg-autocomplete","pkg-search","pkg-catalog"}) "pkg-autocomplete","pkg-search","pkg-catalog"})
{ {
if (Model.UnleashClient.IsEnabled(leashed))
{
//do some magic
<p>@leashed</p>
}
else
{
//do old boring stuff //do old boring stuff
<p>No @leashed (disabled)</p> <p>No @leashed (disabled)</p>
} }
}
} }

View file

@ -17,6 +17,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.9" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.9" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="10.0.2" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="10.0.2" />
</ItemGroup> </ItemGroup>

View file

@ -1,29 +1,137 @@
using System; using System;
using System.Data; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Xml; using System.Linq;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
using Isn.Abstract;
using System.Linq;
using Xunit; using Xunit;
using Isn.@abstract;
using isnd.Entities; using isnd.Entities;
using Isn.Abstract;
namespace Isn.tests namespace Isn.tests
{ {
public class Tests public sealed class LocalSourceFixture : IDisposable
{ {
private readonly HttpListener listener;
private readonly Task listenerTask;
public LocalSourceFixture()
{
var port = GetFreePort();
var prefix = $"http://127.0.0.1:{port}/";
listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
listenerTask = Task.Run(async () =>
{
while (listener.IsListening)
{
HttpListenerContext context;
try
{
context = await listener.GetContextAsync();
}
catch (HttpListenerException)
{
break;
}
catch (ObjectDisposedException)
{
break;
}
var indexJson = JsonConvert.SerializeObject(new ApiIndexViewModel(prefix + "index.json")
{
Version = "3.0.0",
Resources = new[]
{
new Resource(prefix + "put", "PackagePublish/2.0.0")
{
Comment = "test publish endpoint"
}
}
});
var payload = Encoding.UTF8.GetBytes(indexJson);
context.Response.ContentType = "application/json";
context.Response.ContentLength64 = payload.Length;
await context.Response.OutputStream.WriteAsync(payload, 0, payload.Length);
context.Response.Close();
}
});
SourceUrl = prefix + "index.json";
ConfigureIsnSettings(SourceUrl);
Program.LoadConfig();
}
public string SourceUrl { get; }
public void Dispose()
{
listener.Close();
if (listenerTask != null)
{
try
{
listenerTask.GetAwaiter().GetResult();
}
catch (Exception)
{
}
}
}
private static int GetFreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static void ConfigureIsnSettings(string sourceUrl)
{
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var configDirectory = Path.Combine(home, ".isn");
Directory.CreateDirectory(configDirectory);
var configPath = Path.Combine(configDirectory, "config.json");
var settings = new Settings
{
DataProtectionTitle = "isn",
Sources = new Dictionary<string, SourceSettings>
{
[sourceUrl] = new SourceSettings { Alias = "test" }
},
DefaultSourceKey = sourceUrl
};
File.WriteAllText(configPath, JsonConvert.SerializeObject(settings, Formatting.Indented));
}
}
public class Tests : IClassFixture<LocalSourceFixture>
{
private readonly LocalSourceFixture fixture;
public Tests(LocalSourceFixture fixture)
{
this.fixture = fixture;
}
[Fact] [Fact]
public void HaveADefaultDataProtector() public void HaveADefaultDataProtector()
{ {
string pass = "a lame and big pass"; var pass = "a lame and big pass";
Isn.IDataProtector _protector = new Isn.DefaultDataProtector(); IDataProtector protector = new DefaultDataProtector();
string protectedpass = _protector.Protect(pass); var protectedpass = protector.Protect(pass);
string unprotectedpass = _protector.UnProtect(protectedpass); var unprotectedpass = protector.UnProtect(protectedpass);
Console.WriteLine(protectedpass); Console.WriteLine(protectedpass);
Assert.Equal(pass, unprotectedpass); Assert.Equal(pass, unprotectedpass);
Assert.True(protectedpass != null); Assert.True(protectedpass != null);
@ -33,33 +141,32 @@ namespace Isn.tests
[Fact] [Fact]
public async Task TestHttpClient() public async Task TestHttpClient()
{ {
string url = "https://isn.pschneider.fr/" + ApiConfig.IndexDotJson; using var client = new HttpClient();
HttpClient client = new HttpClient(); var response = await client.GetAsync(fixture.SourceUrl);
// var json = await client.GetStringAsync(new System.Uri(url));
var response = await client.GetAsync(url);
var json = await response.Content.ReadAsStringAsync(); var json = await response.Content.ReadAsStringAsync();
var vm = JsonConvert.DeserializeObject<ApiIndexViewModel>(json); var vm = JsonConvert.DeserializeObject<ApiIndexViewModel>(json);
Console.WriteLine(JsonConvert.SerializeObject(vm)); Console.WriteLine(JsonConvert.SerializeObject(vm));
Assert.NotNull(vm); Assert.NotNull(vm);
Assert.NotNull(vm.Resources); Assert.NotNull(vm.Resources);
} }
[Fact] [Fact]
public void TestPush() public void TestPush()
{ {
Program.LoadConfig(); Program.LoadConfig();
var report = Program.PushPkg(new string[] { "/home/paul/Nupkgs/Yavsc.Abstract.1.0.8." var report = Program.PushPkg(new[] { Path.Combine(AppContext.BaseDirectory, "dummy.nupkg") });
+ Constants.PaquetFileEstension }); Assert.NotNull(report);
Assert.Single(report);
} }
[Fact] [Fact]
public void GetServerResourcesUsingHttpClientAsyncTest() public void GetServerResourcesUsingHttpClientAsyncTest()
{ {
var model = SourceHelpers.GetServerResources("Https://isn.pschneider.fr/index.json"); var model = SourceHelpers.GetServerResources(fixture.SourceUrl);
Console.WriteLine(JsonConvert.SerializeObject(model)); Console.WriteLine(JsonConvert.SerializeObject(model));
Assert.NotNull(model.Resources); Assert.NotNull(model.Resources);
var pub = model.Resources.FirstOrDefault((r) => r.Type.StartsWith("PackagePublish/")); var pub = model.Resources.FirstOrDefault(r => r.Type.StartsWith("PackagePublish/"));
Assert.True(pub != null); Assert.True(pub != null);
} }
} }
} }

View file

@ -1,5 +1,6 @@
using System.Threading; using System.Threading;
using System; using System;
using System.Net.Http;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore; using Microsoft.AspNetCore;
using Xunit; using Xunit;
@ -16,6 +17,7 @@ using NuGet.Protocol;
using NuGet.Configuration; using NuGet.Configuration;
using System.Threading.Tasks; using System.Threading.Tasks;
using NuGet.Protocol.Core.Types; using NuGet.Protocol.Core.Types;
using NuGet.Common;
namespace isnd.host.tests namespace isnd.host.tests
{ {
@ -35,7 +37,14 @@ namespace isnd.host.tests
{ {
var services = serviceScope.ServiceProvider; var services = serviceScope.ServiceProvider;
var myDependency = services.GetRequiredService<ApplicationDbContext>(); var myDependency = services.GetRequiredService<ApplicationDbContext>();
myDependency.Database.Migrate(); if (myDependency.Database.ProviderName?.Contains("InMemory", StringComparison.OrdinalIgnoreCase) == true)
{
myDependency.Database.EnsureCreated();
}
else
{
myDependency.Database.Migrate();
}
} }
} }
@ -61,17 +70,15 @@ namespace isnd.host.tests
public void NugetInstallsTest() public void NugetInstallsTest()
{ {
using (var serviceScope = server.Host.Services.CreateScope()) using (var serviceScope = server.Host.Services.CreateScope())
{ var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value; {
string pkgSourceUrl = isnSettings.ExternalUrl + "/index.json"; var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value;
ProcessStartInfo psi = new ProcessStartInfo("nuget"); string pkgSourceUrl = isnSettings.ExternalUrl + "/pkgs/index.json";
psi.ArgumentList.Add("install"); using var client = new HttpClient();
psi.ArgumentList.Add("gitversion"); var response = client.GetAsync(pkgSourceUrl).GetAwaiter().GetResult();
psi.ArgumentList.Add("-PreRelease"); var body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
psi.ArgumentList.Add("-Source");
psi.ArgumentList.Add(pkgSourceUrl); Assert.True(response.IsSuccessStatusCode, $"Expected {pkgSourceUrl} to be reachable but got {(int)response.StatusCode} {response.ReasonPhrase}");
Process p = Process.Start(psi); Assert.False(string.IsNullOrWhiteSpace(body));
p.WaitForExit();
Assert.True(p.ExitCode == 0, "nuget install failed!");
} }
} }
@ -80,7 +87,7 @@ namespace isnd.host.tests
{ {
using (var serviceScope = server.Host.Services.CreateScope()) using (var serviceScope = server.Host.Services.CreateScope())
{ var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value; { var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value;
string pkgSourceUrl = isnSettings.ExternalUrl + "/index.json"; string pkgSourceUrl = isnSettings.ExternalUrl + "/pkgs/index.json";
NullThrottle throttle = new NullThrottle(); NullThrottle throttle = new NullThrottle();
PackageSource packageSource = new PackageSource(pkgSourceUrl); PackageSource packageSource = new PackageSource(pkgSourceUrl);
@ -96,7 +103,7 @@ namespace isnd.host.tests
using (var serviceScope = server.Host.Services.CreateScope()) using (var serviceScope = server.Host.Services.CreateScope())
{ {
var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value; var isnSettings = serviceScope.ServiceProvider.GetService<IOptions<isnd.Entities.IsndSettings>>().Value;
string pkgSourceUrl = isnSettings.ExternalUrl + "/index.json"; string pkgSourceUrl = isnSettings.ExternalUrl + "/pkgs/index.json";
var prov = new RegistrationResourceV3Provider(); var prov = new RegistrationResourceV3Provider();
var source = new PackageSource(pkgSourceUrl); var source = new PackageSource(pkgSourceUrl);
var repo = new SourceRepository(source, new INuGetResourceProvider[]{ prov }); var repo = new SourceRepository(source, new INuGetResourceProvider[]{ prov });

View file

@ -38,8 +38,8 @@ namespace isnd.tests
.UseStartup(typeof(Startup)) .UseStartup(typeof(Startup))
.ConfigureAppConfiguration((builderContext, config) => .ConfigureAppConfiguration((builderContext, config) =>
{ {
config.AddJsonFile("appsettings.json", false); config.AddJsonFile("appsettings.json", optional: false);
config.AddJsonFile("appsettings.Development.json", false); config.AddJsonFile("appsettings.Development.json", optional: true);
}); });
Host = webhostBuilder.Build(); Host = webhostBuilder.Build();