Tests: Add tests for documents

This commit is contained in:
2024-02-13 12:38:37 +01:00
parent 912206f52d
commit 805f782c83
10 changed files with 136 additions and 13 deletions

View File

@ -24,4 +24,6 @@ jobs:
run: $(& dotnet build Tests; $a=$lastexitcode) | findstr x*; exit $a run: $(& dotnet build Tests; $a=$lastexitcode) | findstr x*; exit $a
- name: Run Tests - name: Run Tests
shell: powershell shell: powershell
run: $(& dotnet test Tests; $a=$lastexitcode) | findstr x*; exit $a run: |
$env:PATH += ";$(pwd)\Installer\Files"
$(& dotnet test Tests; $a=$lastexitcode) | findstr x*; exit $a

View File

@ -15,7 +15,7 @@ namespace Elwig.Documents {
// 3 - full // 3 - full
public int DisplayStats = App.Client.ModeDeliveryNoteStats; public int DisplayStats = App.Client.ModeDeliveryNoteStats;
public DeliveryNote(Delivery d, AppDbContext ctx) : base($"Traubenübernahmeschein Nr. {d.LsNr}", d.Member) { public DeliveryNote(Delivery d, AppDbContext? ctx = null) : base($"Traubenübernahmeschein Nr. {d.LsNr}", d.Member) {
UseBillingAddress = true; UseBillingAddress = true;
ShowDateAndLocation = true; ShowDateAndLocation = true;
Delivery = d; Delivery = d;
@ -27,7 +27,7 @@ namespace Elwig.Documents {
$"</tbody></table>"; $"</tbody></table>";
Text = App.Client.TextDeliveryNote; Text = App.Client.TextDeliveryNote;
DocumentId = d.LsNr; DocumentId = d.LsNr;
MemberBuckets = ctx.GetMemberBuckets(d.Year, d.Member.MgNr).GetAwaiter().GetResult(); MemberBuckets = ctx?.GetMemberBuckets(d.Year, d.Member.MgNr).GetAwaiter().GetResult() ?? [];
} }
} }
} }

View File

@ -8,7 +8,7 @@ namespace Elwig.Helpers.Printing {
private static RazorLightEngine? Engine = null; private static RazorLightEngine? Engine = null;
public static bool IsReady => Engine != null; public static bool IsReady => Engine != null;
public static async Task Init(Action evtHandler) { public static async Task Init(Action? evtHandler = null) {
var e = new RazorLightEngineBuilder() var e = new RazorLightEngineBuilder()
.UseFileSystemProject(App.DataPath + "resources") .UseFileSystemProject(App.DataPath + "resources")
.UseMemoryCachingProvider() .UseMemoryCachingProvider()
@ -24,7 +24,7 @@ namespace Elwig.Helpers.Printing {
await e.CompileTemplateAsync("DeliveryConfirmation"); await e.CompileTemplateAsync("DeliveryConfirmation");
Engine = e; Engine = e;
evtHandler(); evtHandler?.Invoke();
} }
public static async Task<string> CompileRenderAsync(string key, object model) { public static async Task<string> CompileRenderAsync(string key, object model) {

View File

@ -11,13 +11,20 @@ using System.Linq;
namespace Elwig.Helpers.Printing { namespace Elwig.Helpers.Printing {
public static class Pdf { public static class Pdf {
private static readonly string PdfToPrinter = App.ExePath + "PDFtoPrinter.exe"; private static readonly string PdfToPrinter = new string[] { App.ExePath }
private static readonly string WinziPrint = App.ExePath + "WinziPrint.exe"; .Union(Environment.GetEnvironmentVariable("PATH")?.Split(';') ?? [])
.Select(x => Path.Combine(x, "PDFtoPrinter.exe"))
.Where(x => File.Exists(x))
.FirstOrDefault() ?? throw new FileNotFoundException("PDFtoPrinter executable not found");
private static readonly string WinziPrint = new string[] { App.ExePath }
.Union(Environment.GetEnvironmentVariable("PATH")?.Split(';') ?? [])
.Select(x => Path.Combine(x, "WinziPrint.exe"))
.Where(x => File.Exists(x))
.FirstOrDefault() ?? throw new FileNotFoundException("WiniPrint executable not found");
private static Process? WinziPrintProc; private static Process? WinziPrintProc;
public static bool IsReady => WinziPrintProc != null; public static bool IsReady => WinziPrintProc != null;
public static async Task Init(Action? evtHandler = null) {
public static async Task Init(Action evtHandler) {
var p = new Process() { StartInfo = new() { var p = new Process() { StartInfo = new() {
FileName = WinziPrint, FileName = WinziPrint,
CreateNoWindow = true, CreateNoWindow = true,
@ -33,7 +40,7 @@ namespace Elwig.Helpers.Printing {
p.StartInfo.ArgumentList.Add("-"); p.StartInfo.ArgumentList.Add("-");
p.Start(); p.Start();
WinziPrintProc = p; WinziPrintProc = p;
evtHandler(); evtHandler?.Invoke();
} }
public static async Task<IEnumerable<int>> Convert(string htmlPath, string pdfPath, bool doubleSided = false, IProgress<double>? progress = null) { public static async Task<IEnumerable<int>> Convert(string htmlPath, string pdfPath, bool doubleSided = false, IProgress<double>? progress = null) {

View File

@ -0,0 +1,31 @@
using Elwig.Documents;
using Elwig.Helpers;
namespace Tests.DocumentTests {
[TestFixture]
public class DeliveryNoteTest {
private readonly AppDbContext Context = new();
[Test]
public async Task Test_01_OneDeliveryPart() {
var d = await Context.Deliveries.FindAsync(2020, 1);
using var doc = new DeliveryNote(d!, Context);
var text = await Utils.GeneratePdfText(doc);
Console.Write(text);
Assert.Multiple(() => {
Assert.That(text, Contains.Substring("""
MUSTERMANN Max
Winzerstraße 1
2223 Hohenruppersdorf
"""));
Assert.That(text, Contains.Substring("1472583")); // Betriebsnummer
Assert.That(text, Contains.Substring("pauschaliert"));
Assert.That(text, Contains.Substring($"Wolkersdorf, am {DateTime.Now:dd.MM.yyyy}"));
Assert.That(text, Contains.Substring("Traubenübernahmeschein Nr. 20201001X001"));
// TODO
Assert.That(text, Contains.Substring("Ich bin der Text, der auf einem Traubenübernahmeschein steht!"));
});
}
}
}

View File

@ -0,0 +1,37 @@
using Elwig.Helpers;
using System.Reflection;
using Microsoft.Data.Sqlite;
using Elwig.Helpers.Printing;
namespace Tests.DocumentTests {
[SetUpFixture]
public class Setup {
private SqliteConnection? Connection;
[OneTimeSetUp]
public async Task SetupDatabase() {
Connection = await AppDbContext.ConnectAsync();
await AppDbContext.ExecuteEmbeddedScript(Connection, Assembly.GetExecutingAssembly(), "Tests.Resources.Sql.DocumentInsert.sql");
}
[OneTimeTearDown]
public async Task TeardownDatabase() {
if (Connection == null) return;
await AppDbContext.ExecuteEmbeddedScript(Connection, Assembly.GetExecutingAssembly(), "Tests.Resources.Sql.DocumentDelete.sql");
await Connection.DisposeAsync();
Connection = null;
}
[OneTimeSetUp]
public async Task SetupPrinting() {
await Html.Init();
await Pdf.Init();
}
[OneTimeTearDown]
public void TeardownPrinting() {
// no teardown needed yet
}
}
}

View File

@ -0,0 +1,20 @@
using Elwig.Documents;
using NReco.PdfRenderer;
namespace Tests.DocumentTests {
public static class Utils {
private static readonly string FileName = Path.Combine(Path.GetTempPath(), "test_document.pdf");
public static async Task<string> GeneratePdfText(Document doc) {
await doc.Generate();
try {
doc.SaveTo(FileName);
var conv = new PdfToTextConverter { CustomArgs = "-raw " };
return conv.GenerateText(FileName);
} finally {
File.Delete(FileName);
}
}
}
}

View File

@ -0,0 +1,5 @@
-- deletes for DocumentTests
DELETE FROM delivery;
DELETE FROM season;
DELETE FROM wine_attribute;

View File

@ -0,0 +1,20 @@
-- inserts for DocumentTests
INSERT INTO wine_attribute (attrid, name, active, max_kg_per_ha, strict, fill_lower) VALUES
('B', 'Bio', TRUE, NULL, FALSE, 0),
('K', 'Kabinett', TRUE, NULL, FALSE, 0);
INSERT INTO season (year, currency, min_kg_per_bs, max_kg_per_bs, penalty_per_kg, penalty_amount, penalty_none, start_date, end_date) VALUES
(2020, 'EUR', 1000, 2000, NULL, NULL, NULL, NULL, NULL);
INSERT INTO modifier (year, modid, ordering, name, abs, rel, standard, quick_select) VALUES
(2020, 'S', 0, 'Geschädigte Trauben', NULL, -0.1, FALSE, FALSE),
(2020, 'A', 0, 'Keine Voranmeldung', -1000, NULL, FALSE, FALSE);
INSERT INTO delivery (mgnr, year, did, date, time, zwstid, lnr) VALUES
(101, 2020, 1, '2020-10-01', NULL, 'X', 1),
(101, 2020, 2, '2020-10-01', NULL, 'X', 2),
(101, 2020, 3, '2020-10-01', NULL, 'X', 3);
INSERT INTO delivery_part (year, did, dpnr, sortid, attrid, weight, kmw, qualid, hkid, kgnr, gerebelt, manual_weighing, spl_check, scale_id, weighing_id, weighing_reason) VALUES
(2020, 1, 1, 'GV', NULL, 4000, 17, 'KAB', 'WLNO', 06109, TRUE, FALSE, FALSE, NULL, NULL, NULL);

View File

@ -4,9 +4,9 @@
<TargetFramework>net8.0-windows</TargetFramework> <TargetFramework>net8.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject> <IsTestProject>true</IsTestProject>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -19,10 +19,11 @@
</Target> </Target>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NReco.PdfRenderer" Version="1.5.3" />
<PackageReference Include="NUnit" Version="4.0.1" /> <PackageReference Include="NUnit" Version="4.0.1" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" /> <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.10.0"> <PackageReference Include="NUnit.Analyzers" Version="4.0.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>