npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cypress-horus-api

v0.0.2

Published

Api para integração entre o Horus e Cypress

Downloads

141

Readme

Etiquetas

MIT License GPLv3 License AGPL License

Stack utilizada

Back-end: Javascript

API Horus Cypress

API de integração entre o framework de testes Cypress e a ferramenta de gestão de testes Horus

Instalação

Instale o pacote no seu projeto Cypress

  npm i cypress-horus-api

Funcionalidades

  • Criação do ciclo de testes
  • Adição dos casos de testes no ciclo informado
  • Execução do teste
  • Upload de evidências

Documentação da API

Criação do ciclo de testes

  POST {BaseURL}/api/createCicleTest

| Parâmetro | Tipo | Descrição | | :---------- | :--------- | :---------------------------------- | | API-KEY-HORUS | Header | Obrigatório. A chave da sua API deve ser passado no header na chamada do end-point | | folder_name | string | Obrigatório. Nome da pasta onde sera criado o ciclo de testes | | email | string | Obrigatório. E-mail usando no horus | description | string | Obrigatório. Descrição que será criado o ciclo de testes | environment_name | string | Obrigatório. Ambiente que será executado o ciclo de testes

Adição dos testes ao ciclo

  POST {BaseURL}/api/AddCaseTest

| Parâmetro | Tipo | Descrição | | :---------- | :--------- | :---------------------------------- | | API-KEY-HORUS | Header | Obrigatório. A chave da sua API deve ser passado no header na chamada do end-point | | case_cicle_key | string | Obrigatório. Chave do ciclo de testes | | case_test_key | string | Obrigatório. Chave do caso de testes | environment_name | string | Obrigatório. Ambiente que será executado o ciclo de testes | email | string | Obrigatório. E-mail usando no horus

Criação da Execução do teste

  POST {BaseURL}/api/createExecutation

| Parâmetro | Tipo | Descrição | | :---------- | :--------- | :---------------------------------- | | API-KEY-HORUS | Header | Obrigatório. A chave da sua API deve ser passado no header na chamada do end-point | | case_cicle_key | string | Obrigatório. Chave do ciclo de testes | | case_test_key | string | Obrigatório. Chave do caso de testes | result | string | Obrigatório. Resultado capturado após a execução do teste

Upload da evidência do teste

  POST {BaseURL}/api/createEvidence

| Parâmetro | Tipo | Descrição | | :---------- | :--------- | :---------------------------------- | | API-KEY-HORUS | Header | Obrigatório. A chave da sua API deve ser passado no header na chamada do end-point | | executionId | string | Obrigatório. Id da execução do criada | | attachment | string | Obrigatório. Arquivo em Base64 | extension | string | Obrigatório. Extensão do arquivo a ser gerado no ato da execução( PNG, TXT)

Configuração e uso

Dentro de cada teste "it" no Cypress, deve adicionar a chave do teste respectivo do Horus

  it('API-T1, displays two todo items by default', () => {
    cy.get('.todo-list li').should('have.length', 3)
    cy.get('.todo-list li').first().should('have.text', 'Pay electric bill')
    cy.get('.todo-list li').last().should('have.text', 'Walk the dog')
  })

Configuração padrão no arquivo cypress.config.js

env: {
    "horus-api": {
        baseUrl: "{URL_BASE_API/api}",
        token: "{token gerado pelo Horus}",
        email: "{email}",
        folder_name: "Automação",
        createdCicleAlways:false/true,
        environmentName:'Dev',
        cicleDefault:'xxx-x01'
    }
  • baseUrl: Url padrão de acesso a API seguido com /api
  • token: Token gerado no Horus deve ser enviado em todas as requisições aos Endpoints no header
  • email: Email usado para acesso ao Horus
  • folder_name: Diretório padrão para armazenar os ciclo de testes criados
  • createdCicleAlways: Parametro true/false, se será criado um novo ciclo em cada execução
  • environmentName: Ambiente padrão onde será criado os ciclos de testes
  • cicleDefault: Com o parâmetro "createdCicleAlways" false deve ser informado uma chave de um ciclo existente

Dentro do metodo "setupNodeEvents", adicionar o seguinte codigo. Será responsável pelo screenshot das telas após cada teste e o arquivo é movido para uma sub-pasta "Horus"

 on('after:screenshot', (details) => {
        const newFolder = 'cypress/screenshots/horus';
        const newName = `${details.name}.png`;
        const newPath = path.join(newFolder, newName);
    
        return fs.move(details.path, newPath, { overwrite: true })
          .then(() => {
            return { path: newPath };
          });
      })

Exemplo de implementação

Criar um arquivo index.js, dentro da pasta de support contendo o conteudo

const TestManagementAPI = require('horus-api-cypress');

const baseURL = Cypress.env('horus-api').baseUrl;
const token = Cypress.env('horus-api').token;
const email = Cypress.env('horus-api').email;
const folder_name = Cypress.env('horus-api').folder_name;
const createCicleAlways = Cypress.env('horus-api').createdCicleAlways;
const environmentName = Cypress.env('horus-api').environmentName;
const cicleDefault = Cypress.env('horus-api').cicleDefault;

const api = new TestManagementAPI(baseURL, token);


afterEach(async function () {
  Cypress.on("uncaught:exception", (err) => {
    throw err;
  });

  const runner = Cypress.mocha.getRunner();
  const resultTest = runner.suite.ctx.currentTest.state;
  const titleTest = runner.suite.ctx.currentTest.title;
  const issueKey = titleTest.substr(0, titleTest.indexOf(",")).trim();
  const currentTest = runner.suite.ctx.currentTest;

  const testOutput = {
    title: currentTest.title,
    state: currentTest.state,
    duration: currentTest.duration,
    error: currentTest.err ? currentTest.err.message : null,
  };


  try {
    let cicleKey =""

    if(createCicleAlways){
      const descriptionCicle = "Ciclo de teste criado via automação";
      const cicleResult = await api.createCicleTest(folder_name, email, descriptionCicle, environmentName);
      cicleKey = cicleResult.cicle.key;
    }else{
      cicleKey = cicleDefault
    }
    const resultAddTest = await api.addCaseTest(cicleKey, issueKey, environmentName, email);
    const resultCreatedExecution = await api.createExecution(cicleKey, issueKey, resultTest)
    console.log("EXECUÇÂO CRIADA:" +JSON.stringify(resultCreatedExecution.execution.id))

    await cy.screenshot(issueKey,{
      capture:"runner",
      overwrite:true,
    }).then(() => {

      const screenshotPath = `cypress/screenshots/horus/${issueKey}.png`;

      cy.readFile(screenshotPath, 'base64').then((imageBase64) => {
        api.sendEvidence(resultCreatedExecution.execution.id, imageBase64,'png').then(response => {
          console.log('Evidência enviada PNG com sucesso:', response);
        }).catch(error => {
          console.error('Erro ao enviar PNG evidência:', error);
        });

        api.sendEvidence(resultCreatedExecution.execution.id, JSON.stringify(testOutput), 'txt').then(response => {
          console.log('Evidência enviada txt com sucesso:', response);
        }).catch(error => {
          console.log('Evidência enviada txt com sucesso:', error);
        });

      });

      
    
    });

  } catch (error) {
    console.error('Erro na operação:', error);
    throw error;
  }
});

Dentro do arquivo e2e.js, adicionar o import do arquivo

import './horus';

Autores

  • Henrique Castro