Hvad er røgtestning? Byg verifikationstest forklaret med eksempler

Dette lyder måske velkendt: nogen skubbede kode til produktion, og nu er en kritisk funktion brudt. Hvordan kan du forhindre, at dette sker i fremtiden?

via GIPHY

I denne vejledning lærer du om røgtest og hvordan det hjælper med at fange bugs. Derefter ryger du test af en webapplikation på en tidsplan og sender alarmer, når test mislykkes. Lad os komme igang!

  1. Hvad er røgtest?
  2. Hvorfor skulle du være ligeglad?
  3. Opret dit projekt
  4. Opret en røgtest
  5. Gennemgå testkoden
  6. Kør din test lokalt
  7. Kør tests i GitHub Actions
  8. Konfigurer alarmer med Slack
  9. Konklusion

1. Hvad er røgafprøvning?

Udtrykket "røgtest" stammer fra reparation af hardware. En enhed blev tændt og ville mislykkes med røgprøven, hvis den kom i brand. ? Røgtest kaldes undertiden "build verification testing".

Når de anvendes til webapplikationer, bekræfter røgtest, at den vigtigste funktionalitet fungerer. For eksempel kan røgtest på Netflix omfatte at logge ind og afspille en video.

Efter design dækker røgforsøg ikke alle permutationer og kanter. De kontrollerer i stedet, at din ansøgning ikke er så ødelagt, at yderligere test ville være spild af tid.

2. Hvorfor skulle du være ligeglad?

Røgtest giver meget værdi i forhold til den nødvendige indsats for at skabe dem. Ifølge Microsoft er røgtest "den mest omkostningseffektive metode til at identificere og rette mangler i software" efter kodevurderinger.

via GIPHY

Bare et par tests af kritiske funktioner som login kan forbedre kvaliteten markant. At teste, hvad brugerne ofte gør, hjælper med at sikre, at applikationens vigtigste brugssager understøttes.

Røgtest giver også dit team tillid til at sende ny kode. Ændringer i din codebase har ofte utilsigtede og ukendte konsekvenser. Røgtest giver ekstra ro i sindet, at din applikation ikke går i stykker, når du frigiver den fantastiske nye funktion.

Hvis du kører røgtest under produktion, kan du også fange bugs, som tidligere tests gik glip af. Selv små forskelle mellem miljøer som iscenesættelse og produktion kan forårsage problemer. Røgtest kan identificere disse problemer, før en kunde gør det.

Kort fortalt giver røgtest dig endnu et lag af beskyttelse mod en dårlig brugeroplevelse. En problemfri applikation hjælper dit team, din virksomhed og dine kunder med at få større succes.

3. Opret dit projekt

Nu hvor vi har lært, hvad røgafprøvning er, lad os bygge en rørledning til røgtestning!

via GIPHY

Denne vejledning forudsætter, at du forstår kommandolinjen, har Node.js og npminstalleret og kender det grundlæggende i JavaScript og Git.

Du kan oprette dine tests i et eksisterende projekt eller oprette et nyt. For at oprette et nyt projekt skal du køre følgende på kommandolinjen.

mkdir smoke_tests cd smoke_tests

Hvis du ikke allerede har gjort det, skal du initialisere dit projekt, så du kan installere Node.js-pakker.

npm init -y

Lad os nu installere de værktøjer, vi har brug for til at oprette vores røgtest. Denne vejledning opretter Playwright- og Jest-tests på en webapplikation. Playwright er et bibliotek bygget af Microsoft til at automatisere Chromium, Firefox og WebKit-browsere. Jest er en ramme til oprettelse og kørsel af JavaScript-test.

For hurtigt at oprette og køre vores tests bruger vi open source QA Wolf-biblioteket, som jeg hjælper med at vedligeholde. QA Wolf konverterer dine browserhandlinger til Playwright / Jest testkode. Det kører også dine tests i en CI-udbyder som GitHub Actions.

Hvis du foretrækker at bruge en anden testramme, kan du stadig følge denne vejledning for at køre dine tests i CI og oprette alarmer.

For at opsætte dit projekt til røgtest skal du køre følgende i din projektmappe.

npm init qawolf

Du bliver bedt om at angive den mappe, hvor dine tests skal gemmes. Tryk på Enter for at bruge standardkataloget .qawolf, eller skriv et andet navn.

? rootDir: Directory to create tests in (.qawolf)

Du vil så se en note i kommandolinjen, der angiver, om dine tests bruger TypeScript. Vores eksempelprojekt har ikke en "tsconfig.json" -fil, så vores tests bruger ikke TypeScript.

TypeScript ✖️ tsconfig.json not found

Det sidste trin er at vælge din CI-udbyder. Denne tutorial bruger GitHub Actions, men du kan vælge en anden udbyder, hvis du vil. Vælg din CI-udbyder på kommandolinjen, og tryk på Enter.

? Choose CI Provider (Use arrow keys) Azure DevOps Bitbucket Pipelines CircleCI ❯ GitHub Actions GitLab CI/CD Jenkins Skip CI setup 

De nødvendige pakker til røgtest (Playwright, Jest og QA Wolf) installeres derefter.

To filer oprettes også i dit projekt. Den første er en workflow-fil til at køre dine tests i CI. Da vi valgte GitHub-handlinger, gemmes denne fil på ".github / workflows / qawolf.yml". Vi vil diskutere denne fil senere.

Der er også en konfigurationsfil oprettet på "qawolf.config.js". Vi har ikke brug for at redigere denne fil, men du kan lære mere om den her.

Når afhængighederne er færdig med installationen, skal du kontrollere, at installationen var vellykket.

npx qawolf howl

4. Opret en røgtest

Nu hvor vores projekt er oprettet, lad os oprette vores første røgtest. I denne vejledning opretter vi en røgtest på TodoMVC, en nem at udføre applikation. Specifikt vil vi teste, at vi kan

  1. Opret en todo-vare,
  2. udfyld det, og
  3. ryd udfyldte todos.

For at oprette vores test bruger vi npx qawolf createkommandoen. Denne kommando tager URL'en til din applikation og et valgfrit testnavn. Ved at køre denne kommando åbnes en Chromium-browser, hvor dine handlinger konverteres til Playwright / Jest-kode.

Kør følgende på kommandolinjen. Du kan eventuelt erstatte //todomvc.com/examples/reactmed en anden URL og myFirstTestmed et andet navn.

npx qawolf create //todomvc.com/examples/react myFirstTest

Åbn din kodeditor, og find din testfil (".qawolf / myFirstTest.test.js" i vores eksempel). Det er her, din testkode oprettes, når du bruger browseren.

Når Chromium-browseren har åbnet for TodoMVC, skal du udføre følgende handlinger.

  1. Klik på todo-input for at fokusere det
  2. Skriv "Opret test!"
  3. Tryk på Enter
  4. Klik for at udføre todo
  5. Klik på "Ryd udført" for at rydde udfyldte todos
  6. På kommandolinjen skal du markere ? Save and Exitog trykke på Enter for at gemme din test

Videoen nedenfor giver et eksempel.

5. Gennemgå testkoden

Lad os nu se på vores testkode. I din kodeeditor skal du åbne din testfil (".qawolf / myFirstTest.test.js" i vores eksempel).

I begyndelsen af ​​vores test importerer vi qawolf. Vi importerer også element selectorsfra ".qawolf / selectors / myFirstTest.json", som vi vil diskutere lidt.

const qawolf = require("qawolf"); const selectors = require("./selectors/myFirstTest.json");

Testen lancerer derefter en dramatiker browser, som i vores tilfælde er en Chromium-browser. Det opretter en ny dramatiker browserContext, som er en inkognito-browsersession. QA Wolf får adgang til den, contextså den kan opdage dine handlinger. Endelig pageoprettes en ny dramatiker , der åbner en ny fane i browseren.

let browser; let page; beforeAll(async () => { browser = await qawolf.launch(); const context = await browser.newContext(); await qawolf.register(context); page = await context.newPage(); });

Selve testen er indeholdt i en Jest- testblok med det navn, du har angivet. Testen navigerer først til TodoMVC URL. Derefter gennemgår de de handlinger, du har foretaget: Opret et todo-element, udfyld det og ryd udførte todos. Hver handling bruger en af ​​Playwrights pagemetoder, ligesom clickog type.

test('myFirstTest', async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); });

Det første argument, der sendes til hver pagemetode, er en HTML-vælger. Denne vælger fortæller Playwright, hvilket element der skal interageres med, f.eks. Todo-input eller "Ryd færdig" -knappen. Disse vælgere importeres fra filen ".qawolf / selectors / myFirstTest.json", som ser ud som følgende.

{ "0_what_needs_to_b_input": "html= ", // ... } 

Every attribute of the element you interacted with, as well as those of its two ancestors, is stored in this file. When you run your test, it will do its best to find a good enough match to the specified HTML. By not relying on a single attribute, your tests are more robust to changes in your front end code.

Playwright page methods also support other types of selectors, such as CSS selectors or text selectors. For example, you can replace selectors["4_button"] in the last step with the CSS selector '.clear-completed'.

test('myFirstTest', async () => { // ... // change this await page.click(selectors["4_button"]); // to this (CSS selector) await page.click('.clear-completed'); });

You can optionally configure QA Wolf to use test attributes like data-qa in the generated code whenever possible. See this guide to learn more.

After the test finishes running, QA Wolf stops recording any videos of the browser if applicable. The browser is also closed.

afterAll(async () => { await qawolf.stopVideos(); await browser.close(); });

Putting it all together, the complete test code looks like this.

const qawolf = require("qawolf"); const selectors = require("./selectors/myFirstTest.json"); let browser; let page; beforeAll(async () => { browser = await qawolf.launch(); const context = await browser.newContext(); await qawolf.register(context); page = await context.newPage(); }); afterAll(async () => { await qawolf.stopVideos(); await browser.close(); }); test("myFirstTest", async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); });

If the test cannot complete the workflow, it will fail. You are welcome to edit your test code, such as by adding assertions. We won't go into that in this tutorial, but here is a guide if you'd like to learn more.

Now that we understand our test code, let's run our test!

6. Run your test locally

Let's run our test locally to make sure it works. In the command line, run the following to run your test(s) with Jest.

npx qawolf test

You should see a Chromium browser open and run the test. Your test will run as fast as possible, so don't be surprised if it runs quickly.

The video below provides an example.

7. Run tests in GitHub Actions

In this tutorial we'll run our tests on a schedule, such as every hour. Running tests on a schedule ensures that your application is working on an ongoing basis. It can also expose periodic issues, or "flakes", that only appear sometimes.

In this tutorial we use GitHub Actions to run our tests. GitHub Actions is a tool to automate software workflows, such as deploying a web service or testing an application.

Review workflow file

When we set up our project, a YAML file called ".github/workflows/qawolf.yml" was created. We'll first briefly go through the different parts of this file. We will then update it so our tests run on a schedule.

The first line of the workflow file names our workflow. This is the name that will show up in GitHub Actions, and you can change it if you like.

name: qawolf

The on key then specifies what event should trigger our tests to run. By default, your tests will run whenever someone pushes to any branch. We will soon edit this to also run our tests on a schedule.

on: push: # test every branch # edit below if you only want certain branches tested branches: "*" # schedule: # # test on schedule using cron syntax # - cron: "0 * * * *" # every hour

The rest of the file defines what GitHub Actions should do when it runs. GitHub Actions will run whatever jobs are listed under the jobs key. In our case we have just one job that runs our tests.

Specifically, our test job installs dependencies, checks out our code, and runs our test command npx qawolf test. After the test(s) run, debug artifacts like console logs and videos are saved.

jobs: test: runs-on: ubuntu-18.04 steps: - name: Install dependencies run: | sudo apt update # chromium dependencies sudo apt-get install libgbm1 # webkit dependencies sudo apt-get install libwoff1 libopus0 libwebp6 libwebpdemux2 libenchant1c2a libgudev-1.0-0 libsecret-1-0 libhyphen0 libgdk-pixbuf2.0-0 libegl1 libgles2 libevent-2.1-6 libnotify4 libvpx5 libxslt1.1 - uses: actions/[email protected] - uses: actions/[email protected] - uses: actions/[email protected] with: path: ~/.npm key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- - run: npm install # - name: Start local server # run: npm run start & npx wait-on //localhost:3000 - run: npx qawolf test --headless env: # configure tests with environment variables QAW_ARTIFACT_PATH: ${{ github.workspace }}/artifacts # you can also use GitHub secrets for environment variables # //help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets # LOGIN_PASSWORD: ${{ secrets.PASSWORD }} - name: Upload Artifacts if: always() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts

Run tests in GitHub Actions

Now that we understand our workflow file a bit better, let's run it in GitHub Actions. If you have not already, create a Git repository for your project. Make sure to ignore node_modules/ in your ".gitignore" file.

git init git add . git commit -m "Initial commit"

Make sure you have created a repository for your project on GitHub. Then push your code to GitHub.

git remote add origin YOUR_REPOSITORY_URL git push -u origin master

See this GitHub repository for an example.

Now go to your GitHub repository and click on the "Actions" tab, which is next to the "Pull Requests" tab.

You will see that your tests are running. This is because our workflow file told GitHub to run our tests whenever anyone pushed to any branch. Click on the workflow run to view details. Note that the name will vary depending on your commit message.

After your test runs, you should see a green check mark indicating that the workflow was successful. You should also see a link to download artifacts (video and logs) under "Artifacts". Click on this link to download test artifacts.

The artifacts are organized with one folder per test. In our example, we only have one test called "myFirstTest.test.js". Open this folder to see browser logs in the file "logs_0_${timestamp}.txt" and a video "video_0_${timestamp}.mp4". The 0 in the file names refers to the page index. If your test involved more than one page, there would be corresponding logs and videos for each additional page.

Now let's update our workflow file to also run our tests on a schedule. In the ".github/workflows/qawolf.yml" file, comment in lines 7-9.

name: qawolf on: push: # test every branch # edit below if you only want certain branches tested branches: "*" schedule: # test on schedule using cron syntax - cron: "0 * * * *" # every hour

These lines tell GitHub to run your tests on a schedule specified using cron syntax. The default value is "0 * * * *", which means run every hour on the hour. Update this value if you would like to use a different time interval.

We will change one more thing about our workflow file. GitHub Actions has a storage limit for artifacts, so we don't want to upload them every time. Instead we will only upload logs and videos when the tests fail. Update line 51 from if: always() to if: failure().

# ... - name: Upload Artifacts if: failure() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts 

Commit your changes and push them to GitHub.

git add . git commit -m "Run tests on a schedule" git push

Now your smoke tests will run every hour on GitHub Actions!

8. Set up alerts with Slack

The last piece of our pipeline is an alerting system that lets us know when our tests fail. In this tutorial we use Slack because it has a free plan. You can also use a service like PagerDuty, which will have a similar setup process.

via GIPHY

If you do not already have a Slack account and workspace, create them now.

Create Slack webhook

We will now create a Slack webhook, which is a URL that allows us to send Slack messages programmatically. We will make a POST request to this URL when our tests fail.

First we need to create a Slack app, which will be responsible for sending our alert messages. Get started by visiting the Slack API website. In the top right hand corner is a green button to "Create New App".

Click on this button and you will be prompted to name your Slack app and choose a workspace. In our example, we call our app "smoke-tests". After you have filled out the form, click the green "Create App" button.

You should be redirected to your app's page in Slack. Make sure you are on the "Basic Information" page under "Settings". Under "Add features and functionality", there is a link for "Incoming Webhooks". Click on this link.

On the Incoming Webhooks page, click on the toggle to turn on incoming webhooks.

You will then be able to see the "Add New Webhook to Workspace" button at the bottom of the page. Click this button to add a new webhook. We will use this webhook to send a Slack message when our tests fail.

You will then be prompted to choose the channel where your messages will be posted. In our example, we select the "alerts" channel. After choosing your channel, click the green "Allow" button.

You will be redirected to the webhooks page. Under "Webhook URLs for Your Workspace", you now should see your webhook URL.

To test your webhook, copy the code under "Sample curl request to post to a channel". It will look something like the following.

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' //hooks.slack.com/services/SECRET

Paste this in the command line and press Enter. You will see the message "Hello, World!" posted to the channel you specified.

Send alert when tests fail

Now that we have our Slack webhook, we need to update our GitHub Actions workflow file. We will add a step that makes a POST request to our webhook when the tests fail.

Rather than paste our webhook URL into our workflow file directly, we will add it to our repository secrets. Secrets are encrypted environment variables that store sensitive information. Keeping our webhook URL secret prevents others from seeing it and potentially using it for evil. ?

Add a new secret under your repository settings. Call your secret SLACK_WEBHOOK_URL, and set its value to your Slack webhook URL. The video below provides an example.

Now let's update our workflow file. At the bottom of the ".github/workflows/qawolf.yml" file, add the following lines. These lines tell GitHub to make a POST request to your Slack webhook when your tests fail. We changed the value passed to "text" from "Hello, World!" to "Smoke tests failed!", but you can use whatever message you like.

Note that we do not use the value of our Slack webhook URL directly, but instead replace it with ${{ secrets.SLACK_WEBHOOK_URL }}.

# ... - name: Upload Artifacts if: failure() uses: actions/[email protected] with: name: qawolf path: ${{ github.workspace }}/artifacts # add the following lines - name: Post Slack Message if: failure() run: | curl -X POST -H 'Content-type: application/json' --data '{"text":"Smoke tests failed!"}' ${{ secrets.SLACK_WEBHOOK_URL }}

If you would like to test that your webhook works, throw an error in your test file ".qawolf/myFirstTest.test.js". Then push your changes to GitHub.

test("myFirstTest", async () => { await page.goto("//todomvc.com/examples/react"); await page.click(selectors["0_what_needs_to_b_input"]); await page.type(selectors["1_what_needs_to_b_input"], "create test!"); await page.press(selectors["2_what_needs_to_b_input"], "Enter"); await page.click(selectors["3_input"]); await page.click(selectors["4_button"]); // add this line throw new Error("demogorgon!"); });

Your test will fail, and a message will be posted in Slack. You will also be able to download artifacts.

Når du er færdig med at teste din webhook, skal du sørge for at fjerne fejlen fra din testkode.

9. Konklusion

Hvis du er kommet så langt, tillykke! ?

via GIPHY

I denne vejledning lærte vi om røgtest og byggede en rørledning til røgtest. Nu kan du være dit teams røgtesthelt! ?

Hvis dit team har brug for hjælp til QA, eller hvis du bare vil chatte, så send mig en linje på [email protected] ?