Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,13 @@ jobs:
# Testcontainers (Docker); GitHub's Windows runners cannot run Linux containers, so Windows runs the Core tests only.
- name: Test
if: runner.os == 'Linux'
run: dotnet test --no-build --configuration Release
run: dotnet test --no-build --configuration Release --solution tests/PythonScriptRunner.SemE2E.slnf

# The panel E2E tests run alone: containers starting or stopping in the other test projects change the host's network
# interfaces, and Chromium then aborts requests in flight with ERR_NETWORK_CHANGED.
- name: Test (panel E2E)
if: runner.os == 'Linux'
run: dotnet test --no-build --configuration Release --project tests/PythonScriptRunner.Panel.E2E.Tests

- name: Upload Playwright traces
if: failure() && runner.os == 'Linux'
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,13 @@ dotnet test --project tests/PythonScriptRunner.Panel.E2E.Tests --no-build # PS
```

Quando um teste falha, o *trace* do Playwright fica em `TestResults/traces` ao lado do assembly de testes
(`npx playwright show-trace <arquivo>.zip`).
(`npx playwright show-trace <arquivo>.zip`). Rode o E2E sozinho: contêineres subindo ou parando em outros projetos de
teste mudam as interfaces de rede e o Chromium aborta requisições com `ERR_NETWORK_CHANGED`. Para todo o resto de uma vez,
use o filtro de solução sem o E2E (é o que o CI faz):

```bash
dotnet test --solution tests/PythonScriptRunner.SemE2E.slnf
```

O teste de desempenho do painel usa ~200 mil execuções; `PSR_PERF_RUNS_PER_DAY=50000` roda o volume médio completo (90 dias).
O documento OpenAPI do painel é comparado com `tests/PythonScriptRunner.Dashboard.Tests/Snapshots/openapi-v1.verified.json`;
Expand Down
11 changes: 10 additions & 1 deletion panel/scripts/check-bundle.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Orçamento do bundle inicial (spec 008): ≤ 500 KB gzip para os arquivos que index.html carrega.
// Monaco e Vue Flow ficam em chunks carregados sob demanda e não entram na conta.
import { readFile } from 'node:fs/promises'
import { readdir, readFile } from 'node:fs/promises'
import { gzipSync } from 'node:zlib'
import { fileURLToPath } from 'node:url'

Expand All @@ -20,3 +20,12 @@ if (total > limit) {
console.error('O bundle inicial passou do orçamento da spec 008.')
process.exit(1)
}

// A CSP do painel só aceita `data:` em imagens: uma fonte embutida seria bloqueada pelo navegador.
const css = (await readdir(`${dist}assets`)).filter((f) => f.endsWith('.css'))
for (const file of css) {
if ((await readFile(`${dist}assets/${file}`, 'utf8')).includes('url(data:font/')) {
console.error(`assets/${file} embute uma fonte como data:, que a CSP do painel bloqueia.`)
process.exit(1)
}
}
23 changes: 23 additions & 0 deletions panel/src/components/auth/LoginForm.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { mount } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
import { beforeEach, describe, expect, it } from 'vitest'
import LoginForm from './LoginForm.vue'

describe('Formulário de login fixo', () => {
beforeEach(() => setActivePinia(createPinia()))

it('Spec008_AC17 na página o usuário já recebe o foco ao montar (quem digita logo não perde a senha)', () => {
const wrapper = mount(LoginForm, { attachTo: document.body })

expect(document.activeElement).toBe(wrapper.find('input[name=name]').element)
wrapper.unmount()
})

it('Spec008_AC19 com o usuário travado (sessão expirada) o campo de usuário não toma o foco', () => {
const wrapper = mount(LoginForm, { attachTo: document.body, props: { lockedName: 'ana' } })

expect(document.activeElement).not.toBe(wrapper.find('input[name=name]').element)
expect(wrapper.find('input[name=name]').attributes('readonly')).toBeDefined()
wrapper.unmount()
})
})
14 changes: 12 additions & 2 deletions panel/src/components/auth/LoginForm.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import type { VTextField } from 'vuetify/components'
import { useSession } from '@/stores/session'

/** Login fixo (D-129): nome + senha; erro genérico (D-135) e contagem regressiva no 429 (D-146). */
Expand All @@ -14,6 +15,7 @@ const password = ref('')
const busy = ref(false)
const invalid = ref(false)
const wait = ref(0)
const nameField = ref<VTextField | null>(null)
let timer: ReturnType<typeof setInterval> | null = null

const canSubmit = computed(() => !busy.value && wait.value === 0 && name.value.trim() !== '' && password.value !== '')
Expand Down Expand Up @@ -56,6 +58,14 @@ async function submit() {
}
}

// Na página o foco vai ao usuário já ao montar: o autofocus do Vuetify espera ~50 ms e tiraria o foco de quem já começou a
// digitar. No diálogo de sessão expirada (usuário travado) fica o autofocus da senha, que espera a transição do diálogo.
onMounted(() => {
if (!props.lockedName) {
nameField.value?.focus()
}
})

onBeforeUnmount(() => timer && clearInterval(timer))
</script>

Expand All @@ -76,13 +86,13 @@ onBeforeUnmount(() => timer && clearInterval(timer))
{{ t('auth.login.throttled', { seconds: wait }) }}
</v-alert>
<v-text-field
ref="nameField"
v-model="name"
:label="t('auth.login.name')"
autocomplete="username"
:readonly="Boolean(lockedName)"
prepend-inner-icon="mdi-account"
name="name"
autofocus
/>
<v-text-field
v-model="password"
Expand Down
2 changes: 1 addition & 1 deletion panel/src/components/fields/FieldBuilder.vue
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ function setColumn(index: number, field: FieldDefinition, column: number, change
</div>
</v-expansion-panel-title>
<v-expansion-panel-text>
<v-row dense>
<v-row density="compact">
<v-col cols="12" md="5">
<v-text-field
:model-value="field.name"
Expand Down
8 changes: 7 additions & 1 deletion panel/src/components/flow/FlowCanvas.vue
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,13 @@ function connectStart(params: { event?: MouseEvent | TouchEvent } & OnConnectSta
}
}

function isValidConnection(connection: Connection): boolean {
function isValidConnection(connection: Connection | Edge): boolean {
// O Vue Flow também valida as arestas recebidas por props (elas têm id); essas vêm do modelo, que já é válido, e
// "ligar numa saída existente" só é proibido para uma conexão nova (sem isso, Organizar sumia com as saídas).
if ('id' in connection) {
return true
}

return (
props.editable &&
Boolean(connection.sourceHandle && connection.targetHandle) &&
Expand Down
28 changes: 28 additions & 0 deletions panel/src/components/flow/flow.css
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,34 @@ button.step-node__port-label {
cursor: not-allowed;
}

/* Controles e minimapa seguem o tema do painel: os estilos do Vue Flow têm cores claras fixas. */
.flow-canvas .vue-flow__controls {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);
}

.flow-canvas .vue-flow__controls-button {
background: rgb(var(--v-theme-surface));
color: rgb(var(--v-theme-on-surface));
border-bottom: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.flow-canvas .vue-flow__controls-button:hover {
background: rgba(var(--v-theme-on-surface), 0.08);
}

.flow-canvas .vue-flow__minimap {
background-color: rgb(var(--v-theme-surface));
border: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
}

.flow-canvas .vue-flow__minimap-mask {
fill: rgba(var(--v-theme-on-surface), 0.08);
}

.flow-canvas .vue-flow__minimap-node {
fill: rgba(var(--v-theme-on-surface), 0.3);
}

.flow-canvas .vue-flow__edge.edge--implicit .vue-flow__edge-path {
stroke-dasharray: 6 4;
opacity: 0.6;
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/OverviewView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function runTitle(run: Schemas['RunSummary']) {
<v-btn variant="text" prepend-icon="mdi-refresh" :loading="busy" @click="load">{{ t('common.refresh') }}</v-btn>
</PageHeader>

<v-row dense>
<v-row density="compact">
<v-col v-for="counter in counters" :key="counter.status" cols="6" md="4" lg="2">
<v-card variant="tonal" :color="statusColor(counter.status)" :data-counter="counter.status">
<v-card-text>
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/audit/AuditView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ onMounted(() => load(true))
<PageHeader :title="t('audit.title')" :subtitle="t('audit.subtitle')" />
<v-card class="mb-4">
<v-card-text>
<v-row dense>
<v-row density="compact">
<v-col cols="12" md="2"
><v-text-field v-model="filters.actor" :label="t('audit.actor')" hide-details clearable
/></v-col>
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/pipelines/PipelineDetailView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ const exportUrl = (v: number) => `${apiBase}/pipelines/${encodeURIComponent(key.
t('common.save')
}}</v-btn>
<div class="text-subtitle-2 mt-6 mb-2">{{ t('pipelines.settings.retention') }}</div>
<v-row dense>
<v-row density="compact">
<v-col cols="6">
<v-text-field
v-model="settings.artifactRetentionDays"
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/pipelines/PipelineEditorView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ function finishPublish() {
>{{ publishError }}</v-alert
>

<v-row v-if="form" dense>
<v-row v-if="form" density="compact">
<v-col cols="12" lg="2">
<v-card :title="t('pipelines.editor.palette')" density="compact">
<v-card-text class="pb-0">
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/pipelines/RunPipelineDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ async function submit() {
<v-card :title="t('pipelines.run.title', { name: pipeline.name })" data-testid="run-dialog">
<v-card-text>
<v-alert v-if="error" type="error" variant="tonal" density="compact" class="mb-3">{{ error }}</v-alert>
<v-row dense>
<v-row density="compact">
<v-col cols="12" md="6">
<v-select
v-model="version"
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/runs/RunListView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ function onScroll({ done: finish }: { done: (status: 'ok' | 'empty' | 'error') =
<PageHeader :title="t('runs.title')" :subtitle="t('runs.subtitle')" />
<v-card class="mb-4">
<v-card-text>
<v-row dense>
<v-row density="compact">
<v-col cols="12" md="3"
><v-text-field v-model="filters.pipelineKey" :label="t('runs.filters.pipeline')" clearable hide-details
/></v-col>
Expand Down
2 changes: 1 addition & 1 deletion panel/src/views/stages/StageEditorView.vue
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ function retry(): Schemas['RetryPolicy'] {
@update:model-value="(v: string) => form && (form.memoryLimitMb = v === '' ? null : Number(v))"
/>
<div class="text-subtitle-2 mt-4 mb-2">{{ t('stages.editor.retry') }}</div>
<v-row dense>
<v-row density="compact">
<v-col cols="4">
<v-text-field
:model-value="retry().maxAttempts"
Expand Down
3 changes: 3 additions & 0 deletions panel/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ export default defineConfig({
outDir: 'dist',
emptyOutDir: true,
chunkSizeWarningLimit: 4096,
// Fontes sempre como arquivo: a CSP do painel (default-src 'self') bloqueia fontes `data:`, e o Vite embutiria os
// subconjuntos pequenos da Roboto.
assetsInlineLimit: (file) => (/\.(woff2?|ttf|otf|eot)$/i.test(file) ? false : undefined),
},
worker: {
format: 'es',
Expand Down
15 changes: 13 additions & 2 deletions tests/PythonScriptRunner.Panel.E2E.Tests/AccessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,23 @@ public async Task Spec008_AC10_Reader_SeesNoActionButtons_AndEditRoutesShowNoPer
[Fact]
public async Task Spec008_AC12_FollowsTheDarkSystemTheme_AndKeepsTheManualChoiceAfterReload()
{
await StartAsync();
await StartAsync(s => s.Worker = false);
await App.ImportFixtureAsync("calculo-progressao");
var page = await OpenAsync(PanelUsers.Reader, o => o.ColorScheme = ColorScheme.Dark);
await GoToAsync(page, string.Empty);
await GoToAsync(page, "trilhas/calculo-progressao");
var app = page.Locator(".v-application");
await Expect(app).ToHaveClassAsync(new Regex(@"\bv-theme--dark\b"));

// The canvas controls and minimap follow the theme (Vue Flow styles them light by default).
await Expect(page.Locator(".vue-flow__minimap")).ToBeVisibleAsync();
var surface = await page.Locator(".flow-canvas").EvaluateAsync<string>("e => getComputedStyle(e).backgroundColor");
foreach (var part in new[] { ".vue-flow__controls-button", ".vue-flow__minimap" })
{
(await page.Locator(part).First.EvaluateAsync<string>("e => getComputedStyle(e).backgroundColor")).ShouldBe(surface, part);
}

await GoToAsync(page, string.Empty);

await page.GetByTestId("theme-menu").ClickAsync();
await page.GetByTestId("theme-light").ClickAsync();
await Expect(app).ToHaveClassAsync(new Regex(@"\bv-theme--light\b"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ public async Task Spec008_AC15_LoginListFormAndRunDetail_HaveNoSeriousOrCritical

private static async Task ExpectAccessibleAsync(IPage page, string screen)
{
// axe reads the colors as rendered: a dialog still fading in blends its labels with the backdrop.
await page.WaitForFunctionAsync(
"() => document.getAnimations().every(a => a.playState !== 'running' || a.effect?.getComputedTiming().endTime === Infinity)");
var result = await page.RunAxe();
var violations = result.Violations
.Where(v => v.Impact is "serious" or "critical")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using System.Diagnostics;

namespace PythonScriptRunner.Panel.E2E.Tests.Infrastructure;

/// <summary>Interactions with the panel widgets that need more than a click (Monaco, Vuetify selects, Vue Flow handles).</summary>
Expand Down Expand Up @@ -47,10 +49,18 @@ public static async Task ChooseAsync(this ILocator scope, string label, string o
await Expect(menu).ToBeVisibleAsync();

// The menu renders only the items in view (virtual scroll): scroll until the option exists, then click it where it is
// (scrolling it into view again would make the list render it anew).
for (var i = 0; i < 20 && await item.CountAsync() == 0; i++)
// (scrolling it into view again would make the list render it anew). The menu may still be opening, so give each
// scroll time to render instead of spending all the attempts at once.
var deadline = Stopwatch.StartNew();
while (await item.CountAsync() == 0)
{
if (deadline.Elapsed > TimeSpan.FromSeconds(15))
{
throw new TimeoutException($"The option '{option}' did not appear in the '{label}' menu.");
}

await menu.EvaluateAsync("menu => [menu, ...menu.querySelectorAll('*')].filter(e => e.scrollHeight > e.clientHeight + 1).forEach(e => e.scrollTop += 120)");
await page.WaitForTimeoutAsync(100);
}

await item.DispatchEventAsync("click");
Expand Down
7 changes: 6 additions & 1 deletion tests/PythonScriptRunner.Panel.E2E.Tests/OperationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public sealed partial class OperationTests(PostgresFixture postgres, BrokerFixtu
[Fact]
public async Task Spec008_AC06_Executor_RunsCalculoProgressao_AndSeesTheNodesChangeLiveUntilSucceeded()
{
await StartAsync();
await StartAsync(s => s.Worker = false);
await App.ImportFixtureAsync("calculo-progressao");
var page = await OpenAsync(PanelUsers.Executor);
await page.Context.AddInitScriptAsync(RecordStepStatuses);
Expand All @@ -36,6 +36,11 @@ public async Task Spec008_AC06_Executor_RunsCalculoProgressao_AndSeesTheNodesCha
await Expect(page).ToHaveURLAsync(RunUrl());
var flow = page.GetByTestId("run-flow");
await Expect(flow.Locator("[data-step]")).ToHaveCountAsync(4);
await Expect(flow.Locator("[data-step][data-status=Pending], [data-step][data-status=Queued]")).ToHaveCountAsync(4);

// The worker starts only once the page shows the run waiting: on a fast machine the first step could otherwise
// finish before the page loads, and its node would only ever be seen as Succeeded.
await App.Environment.StartHostAsync();
await Expect(page.GetByTestId("run-status")).ToHaveAttributeAsync("data-status", "Succeeded", new LocatorAssertionsToHaveAttributeOptions { Timeout = 180_000 });
await Expect(flow.Locator("[data-step][data-status=Succeeded]")).ToHaveCountAsync(4);

Expand Down
21 changes: 21 additions & 0 deletions tests/PythonScriptRunner.Panel.E2E.Tests/PipelineEditorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,27 @@ public async Task Spec008_AC16_TestingTheDraft_FollowsThePipelineTestLive_AndPub
pipeline.Versions.Select(v => (v.Version, v.Status)).ShouldBe([(2, VersionStatus.Draft), (1, VersionStatus.Published)], ignoreOrder: true);
}

[Fact]
public async Task Spec008_AC03_Organize_KeepsEveryConnection_IncludingThePipelineOutputs()
{
await StartAsync(s => s.Worker = false);
await App.ImportFixtureAsync("calculo-progressao");
await App.Host.Admin.CreatePipelineDraftFromAsync("calculo-progressao", 1, PsrEnvironment.Author, Ct);
var page = await OpenAsync(PanelUsers.Author);
await GoToAsync(page, "trilhas/calculo-progressao/editar");
var canvas = page.GetByTestId("pipeline-canvas");
var edges = canvas.Locator(".vue-flow__edge");
var outputs = canvas.Locator(".vue-flow__edge[data-id^='out:']");
await Expect(outputs).ToHaveCountAsync(4);
var before = await edges.CountAsync();

await page.GetByRole(AriaRole.Button, new PageGetByRoleOptions { Name = "Organizar" }).ClickAsync();

await Expect(page.GetByTestId("dirty")).ToBeVisibleAsync();
await Expect(outputs).ToHaveCountAsync(4);
await Expect(edges).ToHaveCountAsync(before);
}

private static ILocator Step(ILocator canvas, string key) => canvas.Locator($"[data-step={key}]");

private static ILocator In(ILocator node, string name) => node.Locator($"[data-handle='in:{name}']");
Expand Down
12 changes: 12 additions & 0 deletions tests/PythonScriptRunner.SemE2E.slnf
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"solution": {
"path": "../PythonScriptRunner.slnx",
"projects": [
"tests/PythonScriptRunner.Core.Tests/PythonScriptRunner.Core.Tests.csproj",
"tests/PythonScriptRunner.Dashboard.Tests/PythonScriptRunner.Dashboard.Tests.csproj",
"tests/PythonScriptRunner.EntityFrameworkCore.Tests/PythonScriptRunner.EntityFrameworkCore.Tests.csproj",
"tests/PythonScriptRunner.RabbitMQ.Tests/PythonScriptRunner.RabbitMQ.Tests.csproj",
"tests/PythonScriptRunner.Worker.Tests/PythonScriptRunner.Worker.Tests.csproj"
]
}
}
Loading