1c/Ox
1
0
mirror of https://github.com/LazarenkoA/Ox.git synced 2025-11-23 21:33:13 +02:00

сохранения отчета в html

This commit is contained in:
Артем
2025-11-08 18:38:24 +03:00
parent 19077d6aa4
commit 275bf1bc89
4 changed files with 26 additions and 21 deletions

View File

@@ -318,7 +318,7 @@ https://github.com/user-attachments/assets/6b5f548f-06bd-4ad5-a199-10ccb4ecf539
Находятся в: Находятся в:
``` ```
<worker_dir>/playwright/<job_id> <worker_dir>/playwright/reports/<job_id>
``` ```
`job_id` - уникальный идентификатор, можно посмотреть в логах воркера. `job_id` - уникальный идентификатор, можно посмотреть в логах воркера.

View File

@@ -1,7 +1,7 @@
import { test, expect } from '@playwright/test'; import { test, expect } from '@playwright/test';
test('Тест свод отчетов', async ({ page }) => { test('Тест свод отчетов', async ({ page }) => {
test.setTimeout(100_000); // секунд только для этого теста test.setTimeout(150_000); // секунд только для этого теста
await page.goto('https://localhost/sko/ru/'); await page.goto('https://localhost/sko/ru/');
await page.locator('#userName').click(); await page.locator('#userName').click();
@@ -14,37 +14,37 @@ test('Тест свод отчетов', async ({ page }) => {
await page.getByText('Ф. 0503737').nth(2).dblclick(); await page.getByText('Ф. 0503737').nth(2).dblclick();
await close(page); await close(page);
await page.waitForTimeout(100); await randSleep(page);
await page.getByText('Нормативно-справочная').click(); await page.getByText('Нормативно-справочная').click();
await page.waitForTimeout(100); await page.waitForTimeout(100);
await page.getByText('Бюджеты').click(); await page.getByText('Бюджеты').click();
await page.waitForTimeout(100); await randSleep(page);
await doubleClickRandomRow(page); await doubleClickRandomRow(page);
await closeButton(page, 'ФормаЗаписатьИЗакрыть') await closeButton(page, 'ФормаЗаписатьИЗакрыть')
await page.waitForTimeout(100); await page.waitForTimeout(100);
const count = await page.locator('[id$="_CommandButtonOK"]').count(); const count = await page.locator('[id$="_CommandButtonOK"]').count();
if(count > 0) { if(count > 0) {
await page.locator('[id$="_CommandButtonOK"]').click(); await page.locator('[id$="_CommandButtonOK"]').last().click();
await closeButton(page, 'ФормаЗаписатьИЗакрыть') await closeButton(page, 'ФормаЗаписатьИЗакрыть')
} }
await page.waitForTimeout(500); await randSleep(page);
await page.getByText('Анализ данных').click(); await page.getByText('Анализ данных').click();
await page.waitForTimeout(500); // пауза await page.waitForTimeout(100); // пауза
await page.locator('#cmd_0_0_txt').click(); await page.locator('#cmd_0_0_txt').click();
await page.waitForTimeout(200); await page.waitForTimeout(100);
await close(page); await close(page);
await randSleep(page);
await page.getByText('Комплект отчетности').click(); await page.getByText('Комплект отчетности').click();
await page.waitForTimeout(200); await page.waitForTimeout(200);
await page.locator('#cmd_2_0_txt').click(); await page.locator('#cmd_2_0_txt').click();
await page.waitForTimeout(1000); await page.waitForTimeout(100);
await page.locator('a[id^="form"][id$="СформироватьОтчет"]').last().click(); await page.locator('a[id^="form"][id$="СформироватьОтчет"]').last().click();
await page.waitForTimeout(1000); await page.waitForTimeout(100);
await close(page); await close(page);
}); });
@@ -106,3 +106,9 @@ async function close(page) {
console.warn('⚠️ Кнопка закрытия не найдена или не кликабельна:', error.message); console.warn('⚠️ Кнопка закрытия не найдена или не кликабельна:', error.message);
} }
} }
async function randSleep(page) {
const delay = Math.floor(Math.random() * 5000)+100;
console.log(`Задержка на ${delay/1000} секунд`)
await page.waitForTimeout(delay);
}

View File

@@ -5,29 +5,24 @@ import (
"embed" "embed"
"fmt" "fmt"
"github.com/pkg/errors" "github.com/pkg/errors"
"math/rand/v2"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"time"
) )
//go:embed resource/* //go:embed resource/*
var staticFS embed.FS var staticFS embed.FS
func (w *Worker) runTest(ctx context.Context, jobID, playwrightDir string) error { func (w *Worker) runTest(ctx context.Context, jobID, playwrightDir string) error {
// небольшая рандомная задержка
time.Sleep(time.Duration(rand.IntN(5)) * time.Second)
w.logger.DebugContext(ctx, "exec run playwright test", "job_id", jobID) w.logger.DebugContext(ctx, "exec run playwright test", "job_id", jobID)
if strings.TrimSpace(w.script) == "" { if strings.TrimSpace(w.script) == "" {
return errors.New("script not filled ") return errors.New("script not filled ")
} }
outDir := filepath.Join(playwrightDir, jobID) outDir := filepath.Join(playwrightDir, "reports", jobID)
_ = os.Mkdir(outDir, os.ModeDir)
f, err := os.CreateTemp(filepath.Join(playwrightDir, "tests"), "*.spec.js") f, err := os.CreateTemp(filepath.Join(playwrightDir, "tests"), "*.spec.js")
if err != nil { if err != nil {
@@ -38,13 +33,17 @@ func (w *Worker) runTest(ctx context.Context, jobID, playwrightDir string) error
defer os.Remove(f.Name()) defer os.Remove(f.Name())
_, file := filepath.Split(f.Name()) _, file := filepath.Split(f.Name())
cmd := exec.CommandContext(ctx, "npx", "playwright", "test", "tests/"+file, "--project", "chromium", "--output", outDir) cmd := exec.CommandContext(ctx, "npx", "playwright", "test", "tests/"+file, "--project", "chromium", "--reporter", "html")
cmd.Dir = playwrightDir cmd.Dir = playwrightDir
cmd.Env = append(os.Environ(), "PLAYWRIGHT_HTML_OPEN=never") // что б не открывался отчет в браузере cmd.Env = append(os.Environ(),
"PLAYWRIGHT_HTML_OPEN=never", // что б не открывался отчет в браузере
"PLAYWRIGHT_HTML_OUTPUT_DIR="+outDir,
"PLAYWRIGHT_VIDEO_MODE=retain-on-failure", // сохранит видео только для fallen тестов
)
_, err = w.cmdRun(ctx, cmd) _, err = w.cmdRun(ctx, cmd)
if err == nil { if err == nil {
_ = os.RemoveAll(outDir) _ = os.RemoveAll(outDir) // если не было ошибки киляем каталог
} }
return err return err
} }

View File

@@ -23,7 +23,7 @@ export default defineConfig({
/* Opt out of parallel tests on CI. */ /* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined, workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */ /* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: [['html', { outputFolder: 'playwright-report', open: 'never' }]], //reporter: [['html', { outputFolder: 'playwright-report', open: 'never' }]],
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: { use: {
/* Base URL to use in actions like `await page.goto('')`. */ /* Base URL to use in actions like `await page.goto('')`. */