Execute testes de dramaturgo usando a IA.
auto-playwright : npm install auto-playwright -D.env : export OPENAI_API_KEY= ' sk-..."auto : import { test , expect } from "@playwright/test" ;
import { auto } from "auto-playwright" ;
test ( "auto Playwright example" , async ( { page } ) => {
await page . goto ( "/" ) ;
// `auto` can query data
// In this case, the result is plain-text contents of the header
const headerText = await auto ( "get the header text" , { page , test } ) ;
// `auto` can perform actions
// In this case, auto will find and fill in the search text input
await auto ( `Type " ${ headerText } " in the search box` , { page , test } ) ;
// `auto` can assert the state of the website
// In this case, the result is a boolean outcome
const searchInputHasHeaderText = await auto ( `Is the contents of the search box equal to " ${ headerText } "?` , { page , test } ) ;
expect ( searchInputHasHeaderText ) . toBe ( true ) ;
} ) ;Inclua os StepOptions digite os valores necessários para se conectar ao Azure OpenAI.
import { test , expect } from "@playwright/test" ;
import { auto } from "auto-playwright" ;
import { StepOptions } from "../src/types" ;
const apiKey = "apikey" ;
const resource = "azure-resource-name" ;
const model = "model-deployment-name" ;
const options : StepOptions = {
model : model ,
openaiApiKey : apiKey ,
openaiBaseUrl : `https:// ${ resource } .openai.azure.com/openai/deployments/ ${ model } ` ,
openaiDefaultQuery : { 'api-version' : "2023-07-01-preview" } ,
openaiDefaultHeaders : { 'api-key' : apiKey }
} ;
test ( "auto Playwright example" , async ( { page } ) => {
await page . goto ( "/" ) ;
// `auto` can query data
// In this case, the result is plain-text contents of the header
const headerText = await auto ( "get the header text" , { page , test } , options ) ;
// `auto` can perform actions
// In this case, auto will find and fill in the search text input
await auto ( `Type " ${ headerText } " in the search box` , { page , test } , options ) ;
// `auto` can assert the state of the website
// In this case, the result is a boolean outcome
const searchInputHasHeaderText = await auto ( `Is the contents of the search box equal to " ${ headerText } "?` , { page , test } , options ) ;
expect ( searchInputHasHeaderText ) . toBe ( true ) ;
} ) ; No mínimo, a função auto requer um prompt de texto simples e um argumento que contém seus objetos page e test (opcional).
auto ( "<your prompt>" , { page , test } ) ; Correndo sem o parâmetro test :
import { chromium } from "playwright" ;
import { auto } from "auto-playwright" ;
( async ( ) => {
const browser = await chromium . launch ( { headless : true } ) ;
const context = await browser . newContext ( ) ;
const page = await context . newPage ( ) ;
// Navigate to a website
await page . goto ( "https://www.example.com" ) ;
// `auto` can query data
// In this case, the result is plain-text contents of the header
const res = await auto ( "get the header text" , { page } ) ;
// use res.query to get a query result.
console . log ( res ) ;
await page . close ( ) ;
} ) ( ) ; Você pode passar um atributo debug como o terceiro parâmetro da função auto . Isso imprimirá o prompt e os comandos executados pelo OpenAI.
await auto ( "get the header text" , { page , test } , { debug : true } ) ; Você também pode definir variável de ambiente AUTO_PLAYWRIGHT_DEBUG=true , o que permitirá a depuração para todas as chamadas de auto .
export AUTO_PLAYWRIGHT_DEBUG=trueTodo navegador que dramaturgo suporta.
Existem opções adicionais que você pode passar como um terceiro argumento:
const options = {
// If true, debugging information is printed in the console.
debug : boolean ,
// The OpenAI model (https://platform.openai.com/docs/models/overview)
model : "gpt-4-1106-preview" ,
// The OpenAI API key
openaiApiKey : 'sk-...' ,
} ;
auto ( "<your prompt>" , { page , test } , options ) ; Dependendo do type de ação (inferido pela função auto ), existem diferentes comportamentos e tipos de retorno.
Uma ação (por exemplo, "Click") é uma interação simulada do usuário com a página, por exemplo, um clique em um link. As ações retornarão `indefinidas 'se tivessem sucesso e lançarão um erro se falharem, por exemplo,
try {
await auto ( "click the link" , { page , test } ) ;
} catch ( e ) {
console . error ( "failed to click the link" ) ;
}Uma consulta retornará os dados solicitados da página como uma string, por exemplo,
const linkText = await auto ( "Get the text of the first link" , { page , test } ) ;
console . log ( "The link text is" , linkText ) ; Uma afirmação é uma pergunta que retornará true ou false , por exemplo,
const thereAreThreeLinks = await auto ( "Are there 3 links on the page?" , {
page ,
test ,
} ) ;
console . log ( `"There are 3 links" is a ${ thereAreThreeLinks } statement` ) ; | Aspecto | Abordagem convencional | Testando com dramaturgo de automóvel |
|---|---|---|
| Acoplamento com marcação | Fortemente ligado à marcação do aplicativo. | Elimina o uso de seletores; As ações são determinadas pelo assistente de IA em tempo de execução. |
| Velocidade de implementação | Implementação mais lenta devido à necessidade de tradução precisa de código para cada ação. | Criação rápida de teste usando instruções simples e simples de texto para ações e afirmações. |
| Lidar com cenários complexos | Automatando cenários complexos é desafiador e propenso a falhas frequentes. | Facilita o teste de cenários complexos, concentrando -se nos resultados dos testes pretendidos. |
| Teste de tempo de escrita | Só pode escrever testes após o desenvolvimento completo da funcionalidade. | Permite uma abordagem de desenvolvimento orientada a testes (TDD), permitindo a redação de testes simultaneamente com ou antes do desenvolvimento da funcionalidade. |
locator.blurlocator.boundingBoxlocator.checklocator.clearlocator.clicklocator.countlocator.filllocator.getAttributelocator.innerHTMLlocator.innerTextlocator.inputValuelocator.isCheckedlocator.isEditablelocator.isEnabledlocator.isVisiblelocator.textContentlocator.uncheckpage.goto Adicionar novas ações é fácil: basta atualizar as functions no src/completeTask.ts .
Esta biblioteca é gratuita. No entanto, existem custos associados ao uso do OpenAI. Você pode encontrar mais informações sobre preços aqui: https://openai.com/pricing/.
Usando https://ray.run/ Como exemplo, o custo da execução de uma etapa de teste é de aproximadamente US $ 0,01 usando o GPT-4 Turbo (e US $ 0,001 usando o GPT-3.5 Turbo).
O baixo custo é em parte porque auto-playwright usa a hérstização de HTML para reduzir o tamanho da carga útil, por exemplo, o que se segue é a carga útil que seria enviada para https://ray.run/.
Naturalmente, o preço variará drasticamente, dependendo da carga útil.
< div class =" cYdhWw dKnOgO geGbZz bGoBgk jkEels " >
< div class =" kSmiQp fPSBzf bnYmbW dXscgu xJzwH jTWvec gzBMzy " >
< h1 class =" fwYeZS fwlORb pdjVK bccLBY fsAQjR fyszFl WNJim fzozfU " >
Learn Playwright
</ h1 >
< h2 class =" cakMWc ptfck bBmAxp hSiiri xJzwS gnfYng jTWvec fzozfU " >
Resources for learning end-to-end testing using Playwright automation
framework
</ h2 >
< div
class =" bLTbYS gvHvKe cHEBuD ddgODW jsxhGC kdTEUJ ilCTXp iQHbtH yuxBn ilIXfy gPeiPq ivcdqp isDTsq jyZWmS ivdkBK cERSkX hdAwi ezvbLT jNrAaV jsxhGJ fzozCb "
> </ div >
</ div >
< div class =" cYdhWw dpjphg cqUdSC fasMpP " >
< a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /blog "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Blog </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Learn in depth subjects about end-to-end testing. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /ask "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Ask AI </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Ask ChatGPT Playwright questions. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /tools "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Dev Tools </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > All-in-one toolbox for QA engineers. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /jobs "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > QA Jobs </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Handpicked QA and Automation opportunities. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /questions "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Questions </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Ask AI answered questions about Playwright. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /discord-forum "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Discord Forum </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Archive of Discord Forum posts about Playwright. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /videos "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Videos </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Tutorials, conference talks, and release videos. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /browser-extension "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > Browser Extension </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > GUI for generating Playwright locators. </ p >
</ div > </ a
> < a
class =" gacSWM dCgFix conipm knkqUc bddCnd dTKJOB leOtqz hEzNkW fNBBKe jTWvec fIMbrO fzozfU group "
href =" /wiki "
> < div class =" plfYl bccLBY hSiiri fNBpvX " > QA Wiki </ div >
< div class =" jqqjPD fWDXZB pKTba bBmAxp hSiiri evbPEu " >
< p > Definitions of common end-to-end testing terms. </ p >
</ div > </ a
>
</ div >
< div
class =" kSmiQp fPSBzf pKTba eTDpsp legDhJ hSiiri hdaZLM jTWvec gzBMzy bGySga fzoybr "
>
< p class =" dXhlDK leOtqz glpWRZ fNCcFz " >
Use < kbd class =" bWhrAL XAzZz cakMWc bUyOMB bmOrOm fyszFl dTmriP " > ⌘ </ kbd > +
< kbd > k </ kbd > + "Tools" to quickly access all tools.
</ p >
</ div >
</ div > A função auto usa Sanitize-Html para higienizar o HTML da página antes de enviá-la para o OpenAI. Isso é feito para reduzir o custo e melhorar a qualidade do texto gerado.
Este projeto se inspira em Zerostep. O ZEROSTEP oferece uma API semelhante, mas com uma implementação mais robusta por meio de seu back -end proprietário. O dramaturgo automático foi criado com o objetivo de explorar a tecnologia subjacente do ZeroStep e estabelecer uma base para uma versão de código aberto de seu software. Para ambientes de produção, sugiro optar por Zerostep.
Aqui está uma comparação lado a lado de dramaturgo de automóvel e zerotep:
| Critérios | Dramaturgo automático | ZEROSTEP |
|---|---|---|
| Usa API OpenAI | Sim | Nº 1 |
| Usa solicitações de texto simples | Sim | Não |
Usa functions sdk | Sim | Não |
| Usa a haixa HTML | Sim | Não |
| Usa API de dramaturgo | Sim | Não 2 |
| Usa capturas de tela | Não | Sim |
| Usa a fila | Não | Sim |
| Usa websockets | Não | Sim |
| Instantâneos | Html | Dom |
| Implementa o paralelismo | Não | Sim |
| Permite rolagem | Não | Sim |
| Fornece acessórios | Não | Sim |
| Licença | Mit | Mit |
MIT License
Copyright (c) 2023 Reflect Software Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Usa a API proprietária da Zerostep. ↩
Usa alguma API de dramaturgo, mas depende predominantemente no Protocolo Chrome Devtools (CDP). ↩