Što je BDD testiranje? Primjer okvira
Što je BDD (Razvoj vođen ponašanjem) testiranje?
BDD (Razvoj vođen ponašanjem) testiranje je tehnika agilnog razvoja softvera i predstavlja proširenje TDD-a, tj. Test Driven Development. U BDD-u su testni slučajevi napisani na prirodnom jeziku koji čak i neprogrameri mogu čitati.
Kako funkcionira BDD testiranje?
Uzmite u obzir da vam je dodijeljeno stvaranje modula Prijenos sredstava u aplikaciji Net Banking.
Postoji više načina za testiranje
- Prijenos sredstava trebao bi se izvršiti ako na izvornom računu ima dovoljno sredstava
- Prijenos sredstava trebao bi se izvršiti ako su podaci o odredišnom klima-uređaju točni
- Prijenos sredstava trebao bi se izvršiti ako je lozinka transakcije / RSA kod / sigurnosna provjera autentičnosti za transakciju koju je unio korisnik ispravna
- Prijenos sredstava trebao bi se izvršiti čak i ako je državni praznik
- Prijenos sredstava trebao bi se izvršiti na datum u budućnosti koji odredi vlasnik računa
Korištenje električnih romobila ističe Testni scenarij postati razrađeniji i složeniji jer uzimamo u obzir dodatne značajke kao što je iznos prijenosa X za interval Y dana/mjeseci, zaustavljanje rasporeda prijenosa kada ukupni iznos dosegne Z, i tako dalje
Opća tendencija programera je da kasnije razviju značajke i napišu testni kod. Kao što je vidljivo u gornjem slučaju, Testni slučaj razvoj za ovaj slučaj je složen i programer će ga odgoditi Ispitivanje do puštanja na slobodu, a tada će obaviti brzo, ali neučinkovito testiranje.
Kako bi se prevladao ovaj problem (Razvoj vođen ponašanjem) zamišljen je BDD. Programeru olakšava cijeli proces testiranja
U BDD, sve što napišete mora ući S obzirom-Kada-Tada korake. Razmotrimo isti gornji primjer u BDD-u
Given that a fund transfer module in net banking application has been developed And I am accessing it with proper authentication
WhenI shall transfer with enough balance in my source account Or I shall transfer on a Bank Holiday Or I shall transfer on a future date And destination a/c details are correct And transaction password/rsa code / security authentication for the transaction is correct And press or click send button
Then amount must be transferred And the event will be logged in log file
Zar nije lako pisati, čitati i razumjeti? Pokriva sve moguće testne slučajeve za modul prijenosa sredstava i može se lako modificirati kako bi se prilagodio više. Također, to je više kao pisanje dokumentacije za modul prijenosa sredstava.
Što je REST API testiranje?
Kako je REST danas postao prilično popularan stil za izradu API-ja, postalo je jednako važno automatizirati testne slučajeve REST API-ja zajedno s testnim slučajevima korisničkog sučelja. Dakle, u osnovi, ovi REST API testiranje uključuje testiranje CRUD (Create-Read-Update-Delete) radnji s metodama POST, GET, PUT i DELETE.
Što je Behave?
Behave je jedan od popularnih Python BDD testni okviri.
Pogledajmo kako funkcionira Behave:
Datoteke sa značajkama piše vaš poslovni analitičar/sponzor/bilo tko s vašim scenarijima ponašanja u njima. Ima format prirodnog jezika koji opisuje značajku ili dio značajke s reprezentativnim primjerima očekivanih ishoda
Ovi koraci scenarija preslikani su s implementacijama koraka upisanim u njih Python.
I po izboru, postoje neke kontrole okoline (kod za pokretanje prije i poslije koraka, scenarija, značajki ili cijelog meča pucanja).
Započnimo s postavljanjem našeg okvira za testiranje automatizacije s Behave:
Postavljanje BDD okvira za testiranje Ponašaj se na Windows
Instalacija:
- Preuzmite i instalirajte Python 3 od https://www.python.org/
- Izvršite sljedeću naredbu na naredbenom retku za ponašanje instalacije
- pip instalirati ponašati se
- IDE: Koristio sam PyCharm Community Edition https://www.jetbrains.com/pycharm/download
Postavljanje projekta:
- Stvorite novi projekt
- Napravite sljedeću strukturu imenika:
Datoteke značajki:
Dakle, napravimo našu datoteku značajki Sample_REST_API_Testing.feature ima značajku kao Izvođenje CRUD operacija na usluzi 'posts'.
U našem primjeru upotrijebio sam http://jsonplaceholder.typicode.com/ objavljuje uzorak usluge REST.
Primjer POST scenarija
Scenario: POST post example ->Here we are considering creating new post item using 'posts' service Given: I set post posts API endpoint ->This is prerequisite for the test which is setting URL of posts service When: I set HEADER param request content type as "application/json." And set request body And send POST HTTP request ->This is actual test step of sending a post request Then: Then I receive valid HTPP response code 201 And Response body "POST" is non-empty-> This is verification of response body
Slično, možete napisati preostale scenarije na sljedeći način:
Sample_REST_API_Testing.feature
Feature: Test CRUD methods in Sample REST API testing framework Background: Given I set sample REST API url Scenario: POST post example Given I Set POST posts api endpoint When I Set HEADER param request content type as "application/json." And Set request Body And Send a POST HTTP request Then I receive valid HTTP response code 201 And Response BODY "POST" is non-empty. Scenario: GET posts example Given I Set GET posts api endpoint "1" When I Set HEADER param request content type as "application/json." And Send GET HTTP request Then I receive valid HTTP response code 200 for "GET." And Response BODY "GET" is non-empty Scenario: UPDATE posts example Given I Set PUT posts api endpoint for "1" When I Set Update request Body And Send PUT HTTP request Then I receive valid HTTP response code 200 for "PUT." And Response BODY "PUT" is non-empty Scenario: DELETE posts example Given I Set DELETE posts api endpoint for "1" When I Send DELETE HTTP request Then I receive valid HTTP response code 200 for "DELETE."
Implementacija koraka
Sada, za korake značajke koji se koriste u gornjim scenarijima, možete upisati implementacije Python datoteke u direktoriju "koraci".
Behave framework identificira funkciju Step pomoću dekoratora koji se podudaraju s predikatom značajke datoteke. Na primjer, dani predikat u datoteci značajki Scenario traži funkciju koraka kojoj je "dan" dekorater. Slično podudaranje događa se za When i Then. Ali u slučaju 'Ali', 'I,' funkcija koraka uzima dekorater kao i prethodni korak. Na primjer, ako 'I' dolazi za Given, odgovarajući dekorater funkcije koraka je @given.
Na primjer, kada se korak za POST može implementirati na sljedeći način:
@when (u'I Set HEADER param request content type as "{header_conent_type}"') Mapping of When, here notice “application/json” is been passed from feature file for "{header_conent_type}” . This is called as parameterization def step_impl (context, header_conent_type): This is step implementation method signature request_headers['Content-Type'] = header_conent_type Step implementation code, here you will be setting content type for request header
Slično, implementacija ostalih koraka u step python datoteci izgledat će ovako:
sample_step_implementation.py
from behave import given, when, then, step import requests api_endpoints = {} request_headers = {} response_codes ={} response_texts={} request_bodies = {} api_url=None @given(u'I set sample REST API url') def step_impl(context): global api_url api_url = 'http://jsonplaceholder.typicode.com' # START POST Scenario @given(u'I Set POST posts api endpoint') def step_impl(context): api_endpoints['POST_URL'] = api_url+'/posts' print('url :'+api_endpoints['POST_URL']) @when(u'I Set HEADER param request content type as "{header_conent_type}"') def step_impl(context, header_conent_type): request_headers['Content-Type'] = header_conent_type #You may also include "And" or "But" as a step - these are renamed by behave to take the name of their preceding step, so: @when(u'Set request Body') def step_impl(context): request_bodies['POST']={"title": "foo","body": "bar","userId": "1"} #You may also include "And" or "But" as a step - these are renamed by behave to take the name of their preceding step, so: @when(u'Send POST HTTP request') def step_impl(context): # sending get request and saving response as response object response = requests.post(url=api_endpoints['POST_URL'], json=request_bodies['POST'], headers=request_headers) #response = requests.post(url=api_endpoints['POST_URL'], headers=request_headers) #https://jsonplaceholder.typicode.com/posts # extracting response text response_texts['POST']=response.text print("post response :"+response.text) # extracting response status_code statuscode = response.status_code response_codes['POST'] = statuscode @then(u'I receive valid HTTP response code 201') def step_impl(context): print('Post rep code ;'+str(response_codes['POST'])) assert response_codes['POST'] is 201 # END POST Scenario # START GET Scenario @given(u'I Set GET posts api endpoint "{id}"') def step_impl(context,id): api_endpoints['GET_URL'] = api_url+'/posts/'+id print('url :'+api_endpoints['GET_URL']) #You may also include "And" or "But" as a step - these are renamed by behave to take the name of their preceding step, so: @when(u'Send GET HTTP request') def step_impl(context): # sending get request and saving response as response object response = requests.get(url=api_endpoints['GET_URL'], headers=request_headers) #https://jsonplaceholder.typicode.com/posts # extracting response text response_texts['GET']=response.text # extracting response status_code statuscode = response.status_code response_codes['GET'] = statuscode @then(u'I receive valid HTTP response code 200 for "{request_name}"') def step_impl(context,request_name): print('Get rep code for '+request_name+':'+ str(response_codes[request_name])) assert response_codes[request_name] is 200 @then(u'Response BODY "{request_name}" is non-empty') def step_impl(context,request_name): print('request_name: '+request_name) print(response_texts) assert response_texts[request_name] is not None # END GET Scenario #START PUT/UPDATE @given(u'I Set PUT posts api endpoint for "{id}"') def step_impl(context,id): api_endpoints['PUT_URL'] = api_url + '/posts/'+id print('url :' + api_endpoints['PUT_URL']) @when(u'I Set Update request Body') def step_impl(context): request_bodies['PUT']={"title": "foo","body": "bar","userId": "1","id": "1"} @when(u'Send PUT HTTP request') def step_impl(context): # sending get request and saving response as response object # response = requests.post(url=api_endpoints['POST_URL'], headers=request_headers) #https://jsonplaceholder.typicode.com/posts response = requests.put(url=api_endpoints['PUT_URL'], json=request_bodies['PUT'], headers=request_headers) # extracting response text response_texts['PUT'] = response.text print("update response :" + response.text) # extracting response status_code statuscode = response.status_code response_codes['PUT'] = statuscode #END PUT/UPDATE #START DELETE @given(u'I Set DELETE posts api endpoint for "{id}"') def step_impl(context,id): api_endpoints['DELETE_URL'] = api_url + '/posts/'+id print('url :' + api_endpoints['DELETE_URL']) @when(u'I Send DELETE HTTP request') def step_impl(context): # sending get request and saving response as response object response = requests.delete(url=api_endpoints['DELETE_URL']) # response = requests.post(url=api_endpoints['POST_URL'], headers=request_headers) #https://jsonplaceholder.typicode.com/posts # extracting response text response_texts['DELETE'] = response.text print("DELETE response :" + response.text) # extracting response status_code statuscode = response.status_code response_codes['DELETE'] = statuscode #END DELETE
Izvođenje testova
Sada smo završili s razvojnim dijelom testne skripte, pa pokrenimo naše testove:
Izvršite sljedeću naredbu na naredbenom retku da pokrenete našu datoteku značajki
C: \Programi\Python\Python37>ponašati se -f lijepo C:\ \features\feature_files_folder\Sample_REST_API_Testing.feature
Ovo će prikazati rezultate izvršenja testa na sljedeći način:
Prikaz izvješća na konzoli
Pogledajmo još jednu cool stvar.
Budući da korisnici uvijek više vole vidjeti rezultate testa u čitljivijem i vidljivijem formatu, neka nam uz pomoć Allure budu izvješća u HTML formatu.
Izvješća
Prvo trebate instalirati Allure Behave formatter [https://docs.qameta.io/allure-report/]:
A sada izvršite sljedeću naredbu:
Za izvještaje
>ponašati se -f json -o Sample_REST_API_Testing.feature
> privlačnost služiti
Ovo će generirati vaše izvješće o rezultatima testa u prezentiranom i informativnom formatu poput ovog:
Izvješće o ispitivanju u HTML formatu
Izvješće o testiranju koje prikazuje rezultate pojedinačnog scenarija
rezime
- BDD je razvoj vođen ponašanjem. To je jedna od tehnika agilnog razvoja softvera.
- REST je danas postao prilično popularan stil za izradu API-ja, postalo je jednako važno automatizirati testne slučajeve REST API-ja zajedno s testnim slučajevima korisničkog sučelja.
- BDD ima format prirodnog jezika koji opisuje značajku ili dio značajke s reprezentativnim primjerima očekivanih ishoda
- Behave framework identificira funkciju Step pomoću dekoratora koji se podudaraju s predikatom značajke datoteke
- Primjeri BDD okvira za testiranje: 1) Cucumber 2) SpecFlow 3) Quantum 4) JBehave 5) Codeception