-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #76 from LeohsPaixao/story/inicia-os-testes-playwr…
…ight Story/inicia os testes playwright
- Loading branch information
Showing
19 changed files
with
460 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
{ | ||
"name": "cypress-ui-tests", | ||
"version": "1.3.0", | ||
"version": "1.3.1", | ||
"description": "Project Tests Cypress", | ||
"author": "Leonardo Paixao <[email protected]>", | ||
"license": "MIT", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
PLAY_BASE_URL = "http://localhost:8181" | ||
PLAY_API_URL = "http://localhost:3001" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
{ | ||
"name": "playwright-ui-tests", | ||
"version": "1.1.5", | ||
"version": "1.2.0", | ||
"description": "Project Tests Playwright", | ||
"author": "Leonardo Paixao <[email protected]>", | ||
"license": "MIT", | ||
|
@@ -10,11 +10,12 @@ | |
"play:open": "playwright test --ui", | ||
"play:report": "playwright show-report" | ||
}, | ||
"dependencies": { | ||
"@faker-js/faker": "^9.2.0", | ||
"dotenv": "^16.4.5" | ||
}, | ||
"devDependencies": { | ||
"@playwright/test": "^1.49.0", | ||
"@types/node": "^22.9.1" | ||
}, | ||
"dependencies": { | ||
"dotenv": "^16.4.5" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { faker } from '@faker-js/faker'; | ||
import { Page } from '@playwright/test'; | ||
import { generateValidCPF } from './generateValidCPF'; | ||
|
||
/** | ||
* Esta função preenche um formulário de usuário com dados gerados aleatoriamente usando Playwright e Faker.js. | ||
* | ||
* @observações | ||
* A função utiliza os atributos data-testid para localizar campos específicos no formulário e digita os dados gerados. | ||
* | ||
* @exemplo | ||
* ```typescript | ||
* fillUserForm(); | ||
* ``` | ||
* | ||
* @retorno {void} A função não retorna nenhum valor. | ||
*/ | ||
export async function fillUserForm(page: Page) { | ||
const cpf = generateValidCPF(); | ||
|
||
const formFields = [ | ||
{ element: page.locator('[data-testid="input-fullname"]'), valor: faker.person.fullName() }, | ||
{ element: page.locator('[data-testid="input-socialname"]'), valor: faker.person.middleName() }, | ||
{ element: page.locator('[data-testid="input-document"]'), valor: cpf }, | ||
{ element: page.locator('[data-testid="input-phone"]'), valor: faker.phone.number({ style: 'national' }) }, | ||
{ element: page.locator('[data-testid="input-email"]'), valor: faker.internet.email({ provider: 'example.qa.solar' }) }, | ||
{ element: page.locator('[data-testid="input-password"]'), valor: '123456' }, | ||
]; | ||
|
||
for (const field of formFields) { | ||
await field.element.waitFor({ state: 'visible' }) | ||
await field.element.fill(field.valor); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
function generateRandomDigits(length: number): string { | ||
return Array.from({ length }, () => Math.floor(Math.random() * 10)).join(''); | ||
} | ||
|
||
function calculateVerifierDigit(base: string): number { | ||
const baseDigits = base.split('').map(Number); | ||
const length = baseDigits.length; | ||
const sum = baseDigits.reduce((acc, digit, index) => acc + digit * (length + 1 - index), 0); | ||
const remainder = sum % 11; | ||
return remainder < 2 ? 0 : 11 - remainder; | ||
} | ||
|
||
function formatCPF(cpf: string): string { | ||
return cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4'); | ||
} | ||
|
||
/** | ||
* Gera um CPF válido (Cadastro de Pessoas Físicas). | ||
* | ||
* @retorna Uma string representando um CPF válido no formato "XXX.XXX.XXX-XX". | ||
* | ||
* @observações | ||
* Esta função utiliza uma combinação de geração aleatória de dígitos, cálculo de dígitos verificadores | ||
* e formatação para criar um CPF válido. O CPF gerado não está associado a nenhuma pessoa real e | ||
* deve ser usado apenas para fins de teste ou demonstração. | ||
* | ||
* O algoritmo utilizado nesta função segue as regras oficiais de geração de CPF: | ||
* 1. Gera uma base aleatória de 9 dígitos. | ||
* 2. Calcula o primeiro dígito verificador usando a base e a fórmula: | ||
* (10 * d1 + 9 * d2 + 8 * d3 + 7 * d4 + 6 * d5 + 5 * d6 + 4 * d7 + 3 * d8 + 2 * d9) mod 11 | ||
* O resultado deve ser 0 ou 11 - resultado. | ||
* 3. Calcula o segundo dígito verificador usando a base, o primeiro dígito verificador e a fórmula: | ||
* (11 * d1 + 10 * d2 + 9 * d3 + 8 * d4 + 7 * d5 + 6 * d6 + 5 * d7 + 4 * d8 + 3 * d9 + 2 * primeiroVerificador) mod 11 | ||
* O resultado deve ser 0 ou 11 - resultado. | ||
* 4. Combina a base, o primeiro dígito verificador e o segundo dígito verificador para formar o CPF final. | ||
* 5. Formata o CPF no padrão brasileiro: "XXX.XXX.XXX-XX". | ||
*/ | ||
export function generateValidCPF(): string { | ||
const baseDigits = generateRandomDigits(9); | ||
const firstVerifier = calculateVerifierDigit(baseDigits); | ||
const secondVerifier = calculateVerifierDigit(baseDigits + firstVerifier); | ||
const cpf = `${baseDigits}${firstVerifier}${secondVerifier}`; | ||
return formatCPF(cpf); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import { Page } from '@playwright/test'; | ||
|
||
/** | ||
* Realiza a operação de login simulando uma requisição POST para o endpoint de login da API. | ||
* Armazena o token recebido e o e-mail no local storage do navegador. | ||
* | ||
* @param {Page} page - A página do Playwright onde o localStorage será definido. | ||
* @param {string} email - O email do usuário para login. | ||
* @param {string} password - A senha do usuário para login. | ||
* @returns {Promise<void>} - Uma promise que é resolvida quando a operação de login é concluída. | ||
*/ | ||
export async function login(page: Page, email: string, password: string): Promise<void> { | ||
|
||
const response = await page.request.fetch(`${process.env.PLAY_API_URL}/login`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json' | ||
}, | ||
data: { | ||
email, | ||
password | ||
} | ||
}) | ||
|
||
const { token } = JSON.parse(await response.text()) | ||
|
||
await page.evaluate(({ email, token }) => { | ||
localStorage.setItem('user-token', token); | ||
localStorage.setItem('user-email', email); | ||
}, { email, token }); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { faker } from '@faker-js/faker'; | ||
import { request } from '@playwright/test'; | ||
import { generateValidCPF } from '../commands/generateValidCPF'; | ||
|
||
/** | ||
* Realiza o mock de criação de um usuário através de requisições HTTP. | ||
*/ | ||
async function mockGenerateUsers(): Promise<void> { | ||
const apiContext = await request.newContext({ | ||
baseURL: `${process.env.PLAY_API_URL}/register`, | ||
}); | ||
|
||
const response = await apiContext.post('/register', { | ||
data: { | ||
fullName: faker.person.fullName(), | ||
socialName: faker.person.lastName(), | ||
document: generateValidCPF(), | ||
docType: 'cpf', | ||
phone: faker.phone.number({ style: 'national' }), | ||
email: faker.internet.email({ provider: 'example.qa.solar' }), | ||
password: '123456', | ||
}, | ||
}); | ||
|
||
if (!response.ok()) { | ||
throw new Error(`Erro ao criar usuário: ${response.status()}`); | ||
} | ||
} | ||
|
||
/** | ||
* Gera múltiplos usuários simulados. | ||
*/ | ||
export async function generateUsers(): Promise<void> { | ||
for (let i = 0; i < 10; i++) { | ||
await mockGenerateUsers(); | ||
} | ||
} |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { expect, test } from '@playwright/test'; | ||
import { login } from '../shared/commands/login'; | ||
import { generateUsers } from '../shared/mocks/generateUsers'; | ||
|
||
test.describe('Tela de listagem de Usuários', () => { | ||
|
||
test.beforeAll(async () => { | ||
await generateUsers(); | ||
}); | ||
|
||
test.beforeEach(async ({ page }) => { | ||
login(page, '[email protected]', '123456'); | ||
await page.goto('/listusers') | ||
await page.waitForURL('/listusers'); | ||
}); | ||
|
||
test('Deveria ser possível visualizar os elementos da tela de listagem de Usuários', async ({ page }) => { | ||
await expect(page.locator('[data-testid="table-users"]')).toBeVisible(); | ||
await expect(page.locator('[data-testid="checkbox-select-all"]')).toBeVisible(); | ||
await page.locator('[data-testid="btn-delete-user"]').scrollIntoViewIfNeeded(); | ||
await expect(page.locator('[data-testid="btn-delete-user"]')).toBeVisible(); | ||
}); | ||
|
||
test('Deveria ser possível selecionar todos os usuários', async ({ page }) => { | ||
const selectAllCheckbox = page.locator('[data-testid="checkbox-select-all"]'); | ||
await selectAllCheckbox.check(); | ||
await expect(selectAllCheckbox).toBeChecked(); | ||
}); | ||
|
||
test('Deveria ser possível selecionar um usuário e excluí-lo', async ({ page }) => { | ||
const userCheckbox = page.locator('[data-testid="checkbox-select-users"]').nth(2); | ||
await userCheckbox.check(); | ||
const deleteButton = page.locator('[data-testid="btn-delete-user"]'); | ||
await deleteButton.scrollIntoViewIfNeeded(); | ||
await deleteButton.click(); | ||
const toastContent = page.locator('[data-testid="toast-content"]').first(); | ||
await expect(toastContent).toBeVisible(); | ||
await expect(toastContent).toHaveText('1 usuário(s) excluído(s) com sucesso!'); | ||
}); | ||
}); |
Oops, something went wrong.