Karate API Yekuedza Chishandiso Cheat Sheet

Karate chishandiso chekuvhura API chishandiso chakagadzirwa ne Peter Thomas kubva kuIntuit. Karate yakavakirwa pamusoro peHttpClient uye Cucumber uye ine yayo DSL yekuita kuti API kuyedza kuve nyore. Kunyangwe yanga iripo kwenguva ingangoita gore, yakura nekukurumidza uye ine zvese kugona kutarisirwa kubva kune API yekuyedza chishandiso.

Nekuti Karate inogara pamusoro pecucumber, inogara nhaka yese mashandiro egango, saka unogona kunyora bvunzo dzako dzeAPI mune yakapusa Kupiwa Kana wozo fomata uye shandisa ese magaka mazwi akakosha senge Feature, Scenario Outline, Scenario, Mienzaniso, Feature kumaka.

Ini ndagadzira iyi cheat sheet kuti ndibatsire chero munhu anobatanidzwa mukuyedza APIs, ndichipa mienzaniso yekushandisa chishandiso cheKarate.

Ndokumbira utarise , iyi cheat sheet rinongova muromo wechando. Karate ine zvimwe zvakawanda zvisina kutaurwa pano. Rondedzero iyi ingori mabasa akajairika anowanzo shandiswa pakuyedza APIs.

Wedzera zvinoenderana (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

Chimiro cheProjekiti

Iwe unogona kuronga uye kuronga yako maven purojekiti seizvi:



karate-config.js

Apa ndipo paunogona kugadzira akasiyana ane chiyero chepasirese. Karate inoverenga iyi faira isati yaita chero chiitiko. Izvi zvinouya zviri nyore kwazvo kana uchichinja nharaunda idzo dzakasiyana dzinoshandiswa munzvimbo dzakasiyana

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; }

Maitiro ekutumira Chikumbiro cheHTTP (Tora, Tumira, Isa, Bvisa, Patch)

@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

Mumuenzaniso uri pamusoro, AM_USERNAME, AM_PASSWORD, AM_HOST, uye AM_AUTHENTICATE_PATH vanobva ku karate-config.js faira.

' 'Inogona kududzirwa sechero ipi yaKupihwa, Rini, Ipapo, Uye, asi kana chiito chikasashanda mamiriro, tinogona kushandisa' '.

’+’ Anoita somubati wevateereri

Muenzaniso uri pamusoro unotumira chisina chinhu chikumbiro chemuviri. Tinogona kungoshandisa ''

Iyo nzira inogona kuve chero inoshanda HTTP chiito (Get, Post, Put, Patch, Delete)

' def ’Inoshandiswa kuchengetedza kukosha mune musiyano.

musoro , url , chikumbiro , nzira , chinzvimbo , mhinduro ese mazwi ekarate anoumba iyo DSL. Kune izere runyorwa rweakakosha mazwi, shanyira Intuit.

Mumuenzaniso uri pamusoro, mhinduro ndeye fomati yeJSON, saka tinogona kushandisa karate's builtin JsonPath notation kuongorora mhinduro.

Kumbira Chaining uine akawanda API mafoni

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

Mumuenzaniso uri pamusoro, wekutanga kufona unoitwa uye authId yakagadziriswa kubva kumhinduro uye ndokuchengetwa musiyano inonzi authId. Isu tinobva tatsiva yechipiri yekubhadhara neye authId yakadzorerwa mukutanga kufona. Isu tinobva tashandisa iyo nyowani yekubhadhara kutumira kune inotevera API kufona.

Maitiro ekuverenga matemplate ekukumbira uye kufonera mamwe maficha maficha

Tinogona kuita kuti zviitiko zvedu zvishandisike uye tigovafonera kubva kune mamwe maficha maficha. Mumuenzaniso uyu, tinogona kugadzira 'generic' gadzira-mushandisi.feature faira uko kwatinogona kutumira iyo gadzira chikumbiro chemushandisi asi nemutumbi wakasiyana wekukumbira

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

Tarira, mumuenzaniso uri pamusoro, tiri kushandisa '__arg' sekukumbira kwemuviri weposvo.

Tinogona kuzodaidza iyo yepamusoro ficha faira uye kupfuura mumuviri unodiwa post, iyo yatinogona kuverenga kubva kune template

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

Iyi iri pamusoro kodhi inoverenga template iri munzvimbo com/example/templates/idm/idm-create-user-template.json uye oichengeta senge musiyano weJSON unonzi myReq

Ipapo isu tinogona kutumira iyo JSON inoshanduka kune imwe ficha faira tichishandisa nzira yekufona.

Iyo template inoita senge

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

Maitiro ekuverenga mamwe maficha maficha - muenzaniso 2

Tinogona kuverenga yakasarudzika mushe mune inonzi ficha faira iyo inopfuudzwa kubva kune yekufona ficha faira

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

Tarira, mumuenzaniso uri pamusoro, tiri kushandisa '__arg.emailAddress' sekukumbira kwemuviri weposvo. Isu tinongofarira kutumira iyo email kero sekukumbira

Tinogona kuzodaidza iri pamusoro ficha faira uye kupfuura mumuviri unodiwa, iyo yatinozoverenga kubva kune template

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

Iyi iri pamusoro kodhi inoburitsa iyo tsamba tsamba kubva kuJSON template. Kana isu tikapfuudza kusiana kune imwe ficha faira, inofanira kunge iri yerudzi JSON, saka iyo inoshanduka emailAddress inofanira kunge iri JSON inoshanda.

Ipapo isu tinogona kutumira iyo JSON inoshanduka kune imwe ficha faira tichishandisa nzira yekufona uye tiri kutumira iyo JSON kusiana, mune ino kesi, emailAddress.

Gadzira Test Runner kirasi

Tinogona kuita zviitiko mufaira refaira tichishandisa maven (izvo zvinobatsira kumhanyisa bvunzo munzvimbo yeCI)

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();
} }

Iyi iri pamusoro kodhi inomhanya ese maficha maficha ayo akakamirwa sa '@FR' asi achiregeredza bvunzo dzese dzakanzi '@ignore'.

Iyo zvakare inogadzira gaka mushumo wekutarisa iwo mhedzisiro yemuedzo unomhanya.

Mhanya bvunzo kubva kumutsara wekuraira kana CI

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

Pano, isu tiri kumhanya iyo TestRunner_FR kirasi uye nekumisikidza nharaunda senge staging.

Dzorera JavaScript mune Feature faira

Mune ficha refaira, isu tinokwanisa kuita JavaScript zvakare

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)

Iyi iri pamusoro kodhi inogadzira yakasarudzika tambo yehurefu gumi uye inoichengeta mune inoshanduka inonzi sessionId.

Dhata Dzinotungamirwa Miedzo

Sezvo Karate yakagara pamusoro pemagaka, kuyedzwa-kunoitwa nedhata kunouya sekutadza

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) |

Muenzaniso uri pamusoro unoshandisa Cucumber's Scenario Outline uye Mienzaniso mazwi akakosha kugadzira data-inotyairwa bvunzo. Kuti uverenge paramende yega yega, isu tinoshandisa mabhureki emakona

Fonera Java kubva pane faira refaira

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

Iyi faira iripamusoro inodaidza nzira yeJava mukirasi inonzi StringUtil. Ipapo inochengetedza mhinduro yeiyo kufona kune otpCode kusiyanisa.