Skip to content

Commit 4a54b28

Browse files
net0wellclaude
andcommitted
test(ef): testes de persistência com PostgreSQL 16 via Testcontainers (spec 004, spec 003)
Um teste por critério de aceite da spec 004 (AC-1 a AC-20) e da spec 003 (AC-10 reprocesso, AC-14 teste de rascunho). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent bdec525 commit 4a54b28

7 files changed

Lines changed: 1030 additions & 0 deletions

File tree

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
using PythonScriptRunner.EntityFrameworkCore.Tests.Infrastructure;
2+
using static PythonScriptRunner.EntityFrameworkCore.Tests.Infrastructure.TestScripts;
3+
4+
namespace PythonScriptRunner.EntityFrameworkCore.Tests;
5+
6+
public sealed class CatalogAdminTests(PostgresFixture postgres, PythonFixture python)
7+
{
8+
private static CancellationToken Ct => TestContext.Current.CancellationToken;
9+
10+
[Fact]
11+
public async Task Spec004_AC03_PublishLocksDependenciesAndAudits()
12+
{
13+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
14+
15+
var published = await host.PublishStageAsync("eco", Echo, [Text("texto")], [Text("texto")], requirements: "six==1.16.0");
16+
17+
published.Status.ShouldBe(VersionStatus.Published);
18+
published.LockedRequirements.ShouldNotBeNull().ShouldContain("six==1.16.0");
19+
published.LockedRequirements.ShouldContain("--hash=sha256:");
20+
published.EnvironmentHash.ShouldNotBeNull().Length.ShouldBe(64);
21+
published.PublishedBy.ShouldBe(PsrTestHost.Author.Subject);
22+
(await host.Admin.GetStageAsync("eco", Ct))!.LatestPublishedVersion.ShouldBe(1);
23+
(await host.ScalarAsync<string>("SELECT actor FROM psr.audit_events WHERE action = 'StagePublished' AND entity_key = 'eco@1'"))
24+
.ShouldBe(PsrTestHost.Author.Subject);
25+
}
26+
27+
[Fact]
28+
public async Task Spec004_AC04_SyntaxErrorReportsLineAndColumnAndKeepsTheDraft()
29+
{
30+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
31+
var draft = await host.Admin.CreateStageAsync(new NewCatalogItem("quebrado", "Quebrado"), PsrTestHost.Author, Ct);
32+
var saved = await host.Admin.SaveStageDraftAsync("quebrado", 1, draft.Data with { Script = "from psrunner import stage\n\ndef run(inputs:\n" },
33+
draft.RowVersion, PsrTestHost.Author, Ct);
34+
35+
var error = await Should.ThrowAsync<ScriptSyntaxException>(() => host.Admin.PublishStageAsync("quebrado", 1, saved.RowVersion, PsrTestHost.Author, Ct));
36+
37+
error.Code.ShouldBe(PsrErrorCodes.ScriptSyntaxError);
38+
error.Line.ShouldBe(3);
39+
error.Column.ShouldNotBeNull();
40+
(await host.Admin.GetStageDraftAsync("quebrado", Ct)).ShouldNotBeNull().Version.ShouldBe(1);
41+
}
42+
43+
[Fact]
44+
public async Task Spec004_AC05_UnknownDependencyFailsWithTheUvMessage()
45+
{
46+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
47+
48+
var error = await Should.ThrowAsync<PsrDomainException>(() =>
49+
host.PublishStageAsync("dependencia", Echo, [Text("texto")], [Text("texto")], requirements: "pacote-inexistente-psr-0000==1.0"));
50+
51+
error.Code.ShouldBe(PsrErrorCodes.DependencyResolutionFailed);
52+
error.Message.ShouldContain("pacote-inexistente-psr-0000");
53+
(await host.Admin.GetStageDraftAsync("dependencia", Ct)).ShouldNotBeNull();
54+
}
55+
56+
[Fact]
57+
public async Task Spec004_AC06_PublishedVersionsAreImmutableAndDraftsCopyThem()
58+
{
59+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
60+
var v1 = await host.PublishStageAsync("eco", Echo, [Text("texto")], [Text("texto")]);
61+
62+
var error = await Should.ThrowAsync<PsrDomainException>(() =>
63+
host.Admin.SaveStageDraftAsync("eco", 1, v1.Data with { Script = "mudou" }, v1.RowVersion, PsrTestHost.Author, Ct));
64+
var draft = await host.Admin.CreateStageDraftFromAsync("eco", 1, PsrTestHost.Author, Ct);
65+
66+
error.Code.ShouldBe(PsrErrorCodes.VersionImmutable);
67+
draft.Version.ShouldBe(2);
68+
draft.Data.Script.ShouldBe(Echo);
69+
draft.Data.Inputs.Single().Name.ShouldBe("texto");
70+
(await Should.ThrowAsync<PsrDomainException>(() => host.Admin.CreateStageDraftFromAsync("eco", 1, PsrTestHost.Author, Ct)))
71+
.Code.ShouldBe(PsrErrorCodes.DraftAlreadyExists);
72+
}
73+
74+
[Fact]
75+
public async Task Spec004_AC07_SecondSaveWithTheSameRowVersionConflicts()
76+
{
77+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
78+
var draft = await host.Admin.CreateStageAsync(new NewCatalogItem("disputado", "Disputado"), PsrTestHost.Author, Ct);
79+
80+
var first = await host.Admin.SaveStageDraftAsync("disputado", 1, draft.Data with { Script = "# autora 1" }, draft.RowVersion, PsrTestHost.Author, Ct);
81+
var error = await Should.ThrowAsync<ConcurrencyConflictException>(() =>
82+
host.Admin.SaveStageDraftAsync("disputado", 1, draft.Data with { Script = "# autora 2" }, draft.RowVersion, Actor.User("outra@teste"), Ct));
83+
84+
error.Code.ShouldBe(PsrErrorCodes.ConcurrencyConflict);
85+
var current = error.Current.ShouldBeOfType<StageDraft>();
86+
current.Data.Script.ShouldBe("# autora 1");
87+
current.RowVersion.ShouldBe(first.RowVersion);
88+
}
89+
90+
[Fact]
91+
public async Task Spec004_AC08_ArchivingAStageUsedByAPublishedPipelineIsBlocked()
92+
{
93+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
94+
await host.PublishStageAsync("eco", Echo, [Text("texto")], [Text("texto")]);
95+
await host.PublishPipelineAsync("usa-eco", EchoPipeline());
96+
97+
var error = await Should.ThrowAsync<VersionReferencedException>(() => host.Admin.ArchiveStageVersionAsync("eco", 1, PsrTestHost.Author, Ct));
98+
99+
error.Code.ShouldBe(PsrErrorCodes.VersionReferenced);
100+
error.Pipelines.ShouldBe(["usa-eco@1"]);
101+
}
102+
103+
[Fact]
104+
public async Task Spec004_AC09_OnlyUnusedStagesCanBeDeleted()
105+
{
106+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
107+
await host.PublishStageAsync("nunca-usado", Echo, [Text("texto")], [Text("texto")]);
108+
await host.PublishStageAsync("eco", Echo, [Text("texto")], [Text("texto")]);
109+
await host.PublishPipelineAsync("usa-eco", EchoPipeline());
110+
await host.PublishStageAsync("executado", Echo, [Text("texto")], [Text("texto")]);
111+
await using (var result = await host.Runner.RunStageAsync("executado", new { texto = "x" }, cancellationToken: Ct))
112+
{
113+
result.EnsureSuccess();
114+
}
115+
116+
await host.Admin.DeleteStageAsync("nunca-usado", Actor.User("admin@teste"), Ct);
117+
118+
(await host.Admin.GetStageAsync("nunca-usado", Ct)).ShouldBeNull();
119+
(await host.ScalarAsync<long>("SELECT count(*) FROM psr.stage_versions v JOIN psr.stages s ON s.id = v.stage_id WHERE s.key = 'nunca-usado'")).ShouldBe(0);
120+
(await Should.ThrowAsync<PsrDomainException>(() => host.Admin.DeleteStageAsync("eco", PsrTestHost.Author, Ct))).Code.ShouldBe(PsrErrorCodes.DeleteNotAllowed);
121+
(await Should.ThrowAsync<PsrDomainException>(() => host.Admin.DeleteStageAsync("executado", PsrTestHost.Author, Ct))).Code.ShouldBe(PsrErrorCodes.DeleteNotAllowed);
122+
}
123+
124+
[Fact]
125+
public async Task Spec004_AC16_PipelineRetentionCannotExceedTheGlobalOne()
126+
{
127+
await using var host = await PsrTestHost.CreateAsync(postgres, python);
128+
var draft = await host.Admin.CreatePipelineAsync(new NewCatalogItem("retida", "Retida"), PsrTestHost.Author, Ct);
129+
var pipeline = (await host.Admin.GetPipelineAsync("retida", Ct))!;
130+
131+
var error = await Should.ThrowAsync<PsrDomainException>(() =>
132+
host.Admin.UpdatePipelineRetentionAsync("retida", new PipelineRetention(30, null), pipeline.RowVersion, PsrTestHost.Author, Ct));
133+
var shorter = await host.Admin.UpdatePipelineRetentionAsync("retida", new PipelineRetention(2, 30), pipeline.RowVersion, PsrTestHost.Author, Ct);
134+
135+
error.Code.ShouldBe(PsrErrorCodes.RetentionExceedsGlobal);
136+
shorter.Retention.ShouldBe(new PipelineRetention(2, 30));
137+
draft.Version.ShouldBe(1);
138+
}
139+
140+
[Fact]
141+
public async Task ImportCreatesDraftsAndExistingKeysGetANewVersion()
142+
{
143+
await using var source = await PsrTestHost.CreateAsync(postgres, python);
144+
await source.PublishStageAsync("eco", Echo, [Text("texto")], [Text("texto")]);
145+
await source.PublishPipelineAsync("usa-eco", EchoPipeline());
146+
using var zip = new MemoryStream();
147+
await source.Admin.ExportPipelineVersionAsync("usa-eco", 1, zip, Ct);
148+
149+
await using var target = await PsrTestHost.CreateAsync(postgres, python);
150+
zip.Position = 0;
151+
var fresh = await target.Admin.ImportAsync(zip, PsrTestHost.Author, Ct);
152+
zip.Position = 0;
153+
var again = await source.Admin.ImportAsync(zip, PsrTestHost.Author, Ct);
154+
155+
fresh.Items.ShouldBe([new ImportedItem("Stage", "eco", 1, true), new ImportedItem("Pipeline", "usa-eco", 1, true)]);
156+
again.Items.ShouldBe([new ImportedItem("Stage", "eco", 2, false), new ImportedItem("Pipeline", "usa-eco", 2, false)]);
157+
var pipelineDraft = (await source.Admin.GetPipelineDraftAsync("usa-eco", Ct))!;
158+
pipelineDraft.Data.Steps.Single().StageVersion.ShouldBe(2, "references follow the stage imported in the same archive");
159+
(await source.Admin.GetStageVersionAsync("eco", 1, Ct))!.Status.ShouldBe(VersionStatus.Published);
160+
zip.Position = 0;
161+
(await Should.ThrowAsync<DefinitionInvalidException>(() => source.Admin.ImportAsync(zip, PsrTestHost.Author, Ct)))
162+
.Code.ShouldBe(PsrErrorCodes.ImportInvalid);
163+
}
164+
165+
private static PipelineDraftData EchoPipeline() => new()
166+
{
167+
Inputs = [Text("texto")],
168+
Steps = [new PipelineStepDefinition("eco", "eco", 1)],
169+
Outputs = [new PipelineOutputDefinition("texto", From.Step("eco", "texto"))],
170+
};
171+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using Npgsql;
2+
using Testcontainers.PostgreSql;
3+
4+
[assembly: AssemblyFixture(typeof(PythonScriptRunner.EntityFrameworkCore.Tests.Infrastructure.PostgresFixture))]
5+
6+
namespace PythonScriptRunner.EntityFrameworkCore.Tests.Infrastructure;
7+
8+
/// <summary>One PostgreSQL 16 container (the minimum supported version) for the whole test run; each test gets its own database.</summary>
9+
public sealed class PostgresFixture : IAsyncLifetime
10+
{
11+
private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:16-alpine").Build();
12+
13+
public async ValueTask InitializeAsync() => await _container.StartAsync();
14+
15+
public async ValueTask DisposeAsync() => await _container.DisposeAsync();
16+
17+
/// <summary>Creates an empty database and returns its connection string.</summary>
18+
public async Task<string> CreateDatabaseAsync()
19+
{
20+
var name = $"psr_{Guid.NewGuid():N}";
21+
await using var connection = new NpgsqlConnection(_container.GetConnectionString());
22+
await connection.OpenAsync();
23+
await using var command = new NpgsqlCommand($"CREATE DATABASE {name}", connection);
24+
await command.ExecuteNonQueryAsync();
25+
return new NpgsqlConnectionStringBuilder(_container.GetConnectionString()) { Database = name, Pooling = true }.ConnectionString;
26+
}
27+
}

0 commit comments

Comments
 (0)