Lembar Cheat Alat Tes API Karate

Karate minangka alat uji API openource sing dikembangake dening Peter Thomas saka Intuit. Karate dibangun ing ndhuwur HttpClient lan Timun lan duwe DSL dhewe supaya tes API gampang banget. Sanajan wis meh setaun, wis diwasa kanthi cepet lan duwe kabeh kemampuan sing diarepake saka alat uji API.

Amarga Karate lenggah ing ndhuwur timun, mula entuk kabeh fungsi timun, dadi sampeyan bisa nulis tes API kanthi format sing diwènèhake nalika Diwenehake Nalika Banjur lan gunakake kabeh tembung kunci timun kayata Feature, Skenario Garis Besar, Skenario, Tuladhane, Tandha Fitur.

Aku wis nggawe sheet cheat iki kanggo nulungi sapa wae sing melu nyoba API, menehi conto cara nggunakake alat Karate.


Tulung dicathet , sheet cheat iki mung pucuk gunung es. Karate duwe akeh fitur liyane sing ora kasebut ing kene. Dhaptar iki mung minangka operasi paling umum sing biasane digunakake nalika nyoba API.

Tambah katergantungan (pom.xml)


UTF-8
3.7.0
1.8
1.8
1.8
0.8.0.RC4
3.13.0


com.intuit.karate
karate-core
${karate.version}


com.intuit.karate
karate-apache
${karate.version}
test


com.intuit.karate
karate-testng
${karate.version}


net.masterthought
cucumber-reporting
${cucumber.reporting.version}
test

Struktur Proyek

Sampeyan bisa ngatur lan nyusun proyek maven kaya iki:




karate-config.js

Ing kene sampeyan bisa nggawe variabel sing duwe lingkup global. Karate maca file iki sadurunge nglakokake skenario apa wae. Iki gampang banget nalika ngoper lingkungan sing variabel tartamtu digunakake kanggo macem-macem lingkungan

function() {
var env = karate.env; // get java system property 'karate.env'
karate.log('karate.env selected environment was:', env);
karate.configure('ssl', true)
if (!env) {
env = 'dev'; //env can be anything: dev, qa, staging, etc.
}
var config = {
env: env,
AM_USERNAME: 'devuser',
AM_PASSWORD: 'devpass',
AM_HOST: 'https://am.'+env+'.example.net',
AM_AUTHENTICATE_PATH: '/am/json/realms/root/authenticate',
IDM_USERNAME: 'devuser',
IDM_PASSWORD: 'devpass',
IDM_HOST: 'https://idm.'+env+'.example.net',
IDM_MANAGED_USER_PATH: '/idm/managed/user',
};
if(env == 'qa') {
config.AM_USERNAME: 'myUserName'
config.AM_PASSWORD: 'myPa55word'
}
if(env == 'live') {
config.AM_USERNAME: 'admin'
config.AM_PASSWORD: 'secret'
}
karate.log('OpenAM Host:', config.AM_HOST);
karate.configure('connectTimeout', 60000);
karate.configure('readTimeout', 60000);
return config; }

Cara ngirim Panjaluk HTTP (Entuk, Kirim, Sijine, Mbusak, Tambalan)

@FR Feature: AM Admin Login
Scenario: Login as Admin to AM and get token
Given header X-OpenAM-Username = AM_USERNAME
Given header X-OpenAM-Password = AM_PASSWORD
Given url AM_HOST + AM_AUTHENTICATE_PATH
And request ''
When method POST
Then status 200
* assert response.tokenId != null
* def tokenId = response.tokenId

Ing conto ing ndhuwur, AM_USERNAME, AM_PASSWORD, AM_HOST, lan AM_AUTHENTICATE_PATH asale saka karate-config.js ngajukake

' 'Bisa ditafsirake minangka diwenehi, Nalika, Banjur, Lan, nanging yen tumindak ora cocog karo konteks, kita bisa nggunakake' '.


’+’ Tumindak minangka operator gabungan

Contone ing ndhuwur ngirim panjaluk awak kirim kosong. Kita mung bisa nggunakake ''

Cara kasebut bisa dadi verba HTTP sing bener (Get, Post, Put, Patch, Delete)

' Def 'Digunakake kanggo nyimpen nilai ing variabel.


header , url , panjaluk , cara , status , tanggepan kabeh tembung kunci karate mbentuk DSL. Kanggo dhaptar lengkap tembung kunci, bukak Intuit.

Ing conto ing ndhuwur, tanggepan yaiku format JSON, mula kita bisa nggunakake notasi JATPath karate sing dibangun kanggo ngrampungake tanggapan.

Nyuwun Chain nganggo macem-macem panggilan API

Feature: request chaining with multiple api calls Scenario: chain request demo
* json req = read('classpath:com/example/templates/idm/create-user-template.json')
* def user = req.givenName
Given header X-Username = 'anonymous'
Given header X-Password = 'anonymous'
Given url AM_HOST + '/some/endpoint
And request ''
When method POST
* def authId = response.authId
* def payload1 =
'''
{'authId':'${authId}','callbacks':[{'type':'NameCallback','output':[{'name':'prompt','value':'Email Address'}],'input':[{'name':'IDToken0','value':'${user}@putsbox.com'}]}]}
'''
* replace payload1
| token
| value |
| ${authId} | authId |
| ${user} | user |
* json mypayload1 = payload1
Given header X-Username = 'anonymous'
Given header X-Password = 'anonymous'
Given url AM_HOST + '/openam/some-other-endpoint
And request mypayload1
When method POST

Ing conto ing ndhuwur, telpon pisanan digawe lan authId diurai saka respons lan disimpen ing variabel sing diarani authId. Banjur kita ngganti muatan liya kanthi authId sing dijupuk ing telpon pisanan. Banjur kita nggunakake muatan anyar kanggo ngirim telpon API sabanjure.

Cara maca template panjaluk lan nelpon file fitur liyane

Kita bisa nggawe skenario bisa digunakake maneh lan nelpon saka file fitur liyane. Ing conto iki, kita bisa nggawe file nggawe-pangguna.feature 'umum' supaya bisa ngirim panjaluk pangguna nanging nganggo panjaluk liyane


Feature: Create User in IDM
Scenario: Create user in IDM with given guid
Given header X-Requested-With = 'Swagger-UI'
Given header X-OpenIDM-Username = IDM_USERNAME
Given header X-OpenIDM-Password = IDM_PASSWORD
Given url IDM_HOST + IDM_MANAGED_USER_PATH
And request __arg
When method POST
Then status 201

Elinga, ing conto ing ndhuwur, kita nggunakake '__arg' minangka panjaluk awak pos.

Banjur bisa nelpon file fitur ing ndhuwur lan pass ing postingan sing dibutuhake, lan sabanjure bisa maca saka cithakan

Feature: Create a user
Scenario: Create user in IDM
* json myReq = read('classpath:com/example/templates/idm/idm-create-user-template.json')
* call read('classpath:com/example/idm/idm-create-user.feature') myReq

Kode ing ndhuwur maca template sing ana ing lokasi com/example/templates/idm/idm-create-user-template.json lan nyimpen minangka variabel JSON sing diarani myReq

Banjur kita bisa ngirim variabel JSON menyang file fitur liyane kanthi nggunakake metode panggilan.


Cithakan katon kaya

{
'mail' : 'david@putsbox.com',
'givenName' : 'david',
'sn' : 'putsbox',
'jobRole' : 'developer',
'telephoneNumber' : '91234567890',
'dob' : '01/02/2010', }

Cara maca file fitur liyane - contone 2

Kita bisa maca variabel tartamtu ing file fitur sing disebut sing dilewati saka file fitur nelpon

Feature: Create User in IDM
Scenario: Create user in IDM with given guid
Given header X-Requested-With = 'Swagger-UI'
Given header X-OpenIDM-Username = IDM_USERNAME
Given header X-OpenIDM-Password = IDM_PASSWORD
Given url IDM_HOST + IDM_MANAGED_USER_PATH
And request __arg.emailAddress
When method POST
Then status 201

Elinga, ing conto ing ndhuwur, kita nggunakake '__arg.emailAddress' minangka panjaluk awak pos. Kita mung kepengin ngirim alamat email minangka panjaluk

Banjur bisa nelpon file fitur ing ndhuwur lan pass ing postingan sing dibutuhake, lan sabanjure bisa maca saka cithakan

Feature: Create a user
Scenario: Create user in IDM
* json myReq = read('classpath:com/example/templates/idm/idm-create-user-template.json')
* json emailAddress = '{'emailAddress': '' +myReq.mail+ ''}'
* call read('classpath:com/example/fr/idm/idm-create-user.feature') emailAddress

Kode ing ndhuwur ngeklik kolom mail saka template JSON. Nalika ngirim variabel menyang file fitur liyane, mesthine kudu jinis JSON, mula emailAddress variabel kudu JSON sing valid.

Banjur kita bisa ngirim variabel JSON menyang file fitur liyane kanthi nggunakake metode panggilan lan ngirim variabel JSON, ing kasus iki, emailAddress.

Gawe kelas Runner Test

Kita bisa nglakokake skenario ing file fitur kanthi nggunakake maven (sing migunani kanggo mbukak tes ing lingkungan CI)

import com.intuit.karate.cucumber.CucumberRunner; import com.intuit.karate.cucumber.KarateStats; import cucumber.api.CucumberOptions; import net.masterthought.cucumber.Configuration; import net.masterthought.cucumber.ReportBuilder; import org.apache.commons.io.FileUtils; import org.testng.annotations.Test; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.testng.AssertJUnit.assertTrue; @CucumberOptions(tags = {'@FR', '~@ignore'}) public class TestRunner_FR {
@Test
public void testParallel() {
String karateOutputPath = 'target/cucumber-html-reports';
KarateStats stats = CucumberRunner.parallel(getClass(), 1, karateOutputPath);
generateReport(karateOutputPath);
assertTrue('there are scenario failures', stats.getFailCount() == 0);
}
private static void generateReport(String karateOutputPath) {
Collection jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {'json'}, true);
List jsonPaths = new ArrayList(jsonFiles.size());
for (File file : jsonFiles) {

jsonPaths.add(file.getAbsolutePath());
}
Configuration config = new Configuration(new File('target'), 'YOUR PROJECT NAME');
config.addClassifications('Environment', System.getProperty('karate.env'));
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
} }

Kode ing ndhuwur mbukak kabeh file fitur sing diwenehi tag minangka '@FR' nanging ora nggatekake kabeh tes sing diwenehi tag minangka '@ignore'.

Iki uga nggawe laporan timun kanggo nggambarake asil tes sing ditindakake.

Jalanake tes saka baris perintah utawa CI

mvn clean test -DargLine='-Dkarate.env=staging' -Dtest=TestRunner_FR

Ing kene, kita mbukak kelas TestRunner_FR lan nyetel lingkungan minangka pementasan.

Jalanake JavaScript ing file Feature

Ing file fitur, kita uga duwe kemampuan nglakokake javascript

Feature: Generate a random session id
Scenario: generate random session id
* def random_string =
'''
function(s) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
for (var i = 0; i < s; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
'''
* def sessionId = random_string(10)

Kode ing ndhuwur ngasilake string acak dawane 10 lan nyimpen ing variabel sing diarani sessionId.

Tes sing Didhukung Data

Amarga Karate lungguh ing ndhuwur timun, pengujian adhedhasar data minangka standar

Feature: Data driven testing example Scenario Outline: An 'Invalid input request' error is returned if required parameters have incorrect values.
* def attribute_name = ''
* xml malformed_request =
* json activate_request = malformed_request
* def activate_response = call read('activate.feature') activate_request
* match activate_response.contentType == 'text/xml;charset=ISO-8859-1'
* match activate_response.gas_version == '5.2.7'
* match activate_response.error_code == '1000'
Examples:
| name_attribute | method_call













|
| auth_method
| Java.type('com.example.StringUtil').removeNodeByAttribute(xml_req, attribute_name) |
| app_url
| Java.type('com.example.StringUtil').removeNodeByAttribute(xml_req, attribute_name) |

Tuladha ing ndhuwur nggunakake Outline Skenario Timun lan Conto tembung kunci kanggo nggawe tes adhedhasar data. Kanggo maca saben paramèter, kita nggunakake kurung sudut

Nelpon Java saka file fitur

package com.example; public class StringUtil {
public static String getNumberFromString(String text) {
return text.replaceAll('\D+', '');
} }
Feature: Call java demo Scenario: Get number from text
Given url 'https://preview.putsbox.com/p/david/last.json'
When method GET
* def emailText = response.text
* def otpCode = Java.type('com.example.StringUtil').getNumberFromString(emailText)
* print otpCode

File fitur ing ndhuwur nyebutake metode Java ing kelas sing diarani StringUtil. Banjur nyimpen respon saka variabel panggilan otpCode kasebut.