BDD Testi Nedir? Çerçeve Örneği
BDD (Davranış Odaklı Gelişim) Testi Nedir?
BDD (Davranış odaklı geliştirme) Testi çevik bir yazılım geliştirme tekniğidir ve TDD'nin, yani Test Odaklı Geliştirmenin bir uzantısıdır. BDD'de test senaryoları programcı olmayanların bile okuyabileceği doğal bir dilde yazılır.
BDD Testi nasıl çalışır?
Bir Net Bankacılık uygulamasında Fon Transferi modülünü oluşturmakla görevlendirildiğinizi düşünün.
Bunu test etmenin birden fazla yolu var
- Kaynak hesapta yeterli bakiye olması durumunda Fon Transferi gerçekleşmelidir
- Hedef hesap bilgileri doğruysa Para Transferi yapılmalıdır
- Kullanıcının girdiği işleme ilişkin işlem şifresi/rsa kodu/güvenlik kimlik doğrulaması doğruysa Fon Transferi gerçekleşmelidir
- Fon Transferi Resmi Tatil Olsa Bile Gerçekleştirilmelidir
- Fon Transferi, hesap sahibi tarafından belirlenen ileri bir tarihte yapılmalıdır.
The Test Senaryosu X miktarını Y gün/ay aralığında transfer etme, toplam miktar Z'ye ulaştığında zamanlanmış transferi durdurma vb. gibi ek özellikleri göz önünde bulundurduğumuzda daha ayrıntılı ve karmaşık hale gelir
Geliştiricilerin genel eğilimi, özellikleri geliştirmek ve test kodunu daha sonra yazmaktır. Yukarıdaki durumda da görüldüğü gibi, Test Durumu Bu dava için geliştirme karmaşıktır ve geliştirici erteleyecektir Test yapmak serbest bırakılana kadar, bu noktada hızlı ama etkisiz testler yapacak.
Bu sorunun üstesinden gelmek için (Davranış Odaklı Geliştirme) BDD tasarlandı. Bir geliştirici için tüm test sürecini kolaylaştırır
BDD'de ne yazarsanız yazın Verilen-Ne Zaman-Sonra adımlar. Yukarıdaki aynı örneği BDD'de ele alalım
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
Yazmak, okumak, anlamak kolay değil mi? Fon transferi modülüne ilişkin olası tüm test senaryolarını kapsar ve daha fazlasını barındıracak şekilde kolaylıkla değiştirilebilir. Ayrıca, daha çok fon transferi modülü için dokümantasyon yazmaya benziyor.
REST API Testi nedir?
REST, günümüzde API oluşturmak için oldukça popüler bir stil haline geldiğinden, REST API test senaryolarını UI test senaryolarıyla birlikte otomatikleştirmek de aynı derecede önemli hale geldi. Yani temel olarak bunlar REST API testi CRUD (Oluştur-Oku-Güncelle-Sil) eylemlerinin sırasıyla POST, GET, PUT ve DELETE yöntemleriyle test edilmesini içerir.
Davranış nedir?
Davranış popüler olanlardan biridir Python BDD test çerçeveleri.
Behave'in nasıl çalıştığını görelim:
Özellik dosyaları, İş Analistiniz / Sponsorunuz / kim olursa olsun, davranış senaryolarınız ile birlikte yazılır. Beklenen sonuçları temsil eden örneklerle bir özelliği veya özelliğin bir kısmını açıklayan doğal bir dil formatına sahiptir.
Bu Senaryo adımları, içinde yazılan adım uygulamalarıyla eşlenir. Python.
Ve isteğe bağlı olarak bazı çevresel kontroller (adımlar, senaryolar, özellikler veya tüm atış karşılaşmasından önce ve sonra çalıştırılacak kodlar) vardır.
Behave ile otomasyon test çerçevemizin kurulumuna başlayalım:
BDD Test Çerçevesi Davranışını Ayarlama Windows
Kurulum:
- Python dan 3 https://www.python.org/
- Behavior'u yüklemek için komut isteminde aşağıdaki komutu çalıştırın
- pip kurulum davranışı
- IDE: PyCharm Community Edition'ı kullandım https://www.jetbrains.com/pycharm/download
Proje Kurulumu:
- Yeni bir proje oluştur
- Aşağıdaki Dizin Yapısını Oluşturun:
Özellik Dosyaları:
Öyleyse özellik dosyamızı oluşturalım Sample_REST_API_Testing.özelliği 'Post' servisinde CRUD işlemlerini gerçekleştirme özelliğine sahip.
Örneğimizde kullandım http://jsonplaceholder.typicode.com/ örnek REST Hizmeti yayınlar.
Örnek POST senaryosu
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
Benzer şekilde geri kalan Senaryoları da aşağıdaki gibi yazabilirsiniz:
Sample_REST_API_Testing.özelliği
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."
Adımların Uygulanması
Artık yukarıdaki senaryolarda kullanılan özellik Adımları için uygulamaları yazabilirsiniz. Python “adımlar” dizinindeki dosyalar.
Behave çerçevesi, özellik dosyası yüklemesiyle eşleşen dekoratörler tarafından Step işlevini tanımlar. Örneğin, Özellik dosyası Senaryosundaki Verilen yüklem, dekoratörün "verildiği" adım fonksiyonunu arar. Benzer eşleştirme When ve Then için de geçerlidir. Ancak 'Ama', 'Ve' durumunda, Adım işlevi dekoratörü önceki adımla aynı şekilde alır. Örneğin, Given için 'And' gelirse, eşleşen adım fonksiyonu dekoratörü @given olur.
Örneğin, POST adımı şu şekilde uygulanabildiğinde:
@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
Benzer şekilde, adım python dosyasındaki diğer adımların uygulanması da şöyle görünecektir:
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
Testleri Çalıştırma
Artık test betiği geliştirme kısmımız bitti, hadi testlerimizi çalıştıralım:
Özellik dosyamızı çalıştırmak için komut isteminde aşağıdaki komutu çalıştırın
C: \Programlar\Python\Python37>güzel davran C:\ \features\feature_files_folder\Sample_REST_API_Testing.özelliği
Bu, test yürütme sonuçlarını aşağıdaki gibi gösterecektir:
Konsolda rapor ekranı
Burada harika bir şeye daha bakalım.
Kullanıcılar her zaman test sonuçlarını daha okunaklı ve sunulabilir bir formatta görmeyi tercih ettiğinden, Allure'un yardımıyla raporları HTML formatında alalım.
Raporlar
Öncelikle Allure Behave formatlayıcıyı kurmanız gerekiyor [https://docs.qameta.io/allure-report/]:
Ve şimdi şu komutu çalıştırın:
Raporlar için
>davran -f json -o Sample_REST_API_Testing.özelliği
> çekici hizmet
Bu, test sonuçları raporunuzu şu şekilde sunulabilir ve bilgilendirici formatta oluşturacaktır:
HTML Formatında Test Raporu
Bireysel Senaryo sonucunu gösteren Test Raporu
ÖZET
- BDD Davranış odaklı bir geliştirmedir. Çevik yazılım geliştirme tekniklerinden biridir.
- REST, günümüzde API oluşturmak için oldukça popüler bir stil haline geldi; REST API test senaryolarını, kullanıcı arayüzü test senaryolarıyla birlikte otomatikleştirmek de aynı derecede önemli hale geldi.
- BDD, beklenen sonuçların temsili örnekleriyle bir özelliği veya özelliğin bir kısmını açıklayan doğal bir dil formatına sahiptir.
- Behave çerçevesi, özellik dosyası yüklemi ile eşleşen dekoratörler tarafından Step işlevini tanımlar
- BDD Test Çerçevelerine Örnekler: 1) Cucumber 2) SpecFlow 3) Quantum 4) JBehave 5) Kod Algılama