2012-05-29 12 views
10

Soy un principiante en REST y en el departamento de pruebas. Necesitaba escribir scripts de automatización para probar nuestros servicios REST. Estamos planeando ejecutar estos scripts desde un trabajo de Jenkins CI regularmente. Prefiero escribir esto en python porque ya tenemos scripts de prueba de funcionalidad UI en python generados por IDE de selenio, pero estoy abierto a cualquier buena solución. Comprobé httplib, simplejson y Xunit, pero busco mejores soluciones disponibles. Y también, preferiría escribir una plantilla y generar una secuencia de comandos real para cada API de REST leyendo la información de la API de xml o algo así. Gracias por adelantado a todos los consejos.Asesoramiento necesario para automatizar la prueba de servicios REST

+0

¿Qué es exactamente estás tratando de probar? Que la respuesta es lo que esperarías? – Swift

+0

Sí, es necesario verificar los datos de respuesta. Pensando en probar todas las acciones de api de CRUD. Por ejemplo, al usar API REST, crear cinco empleados, leer a los empleados, actualizar algunos y finalmente eliminar todos ... Estoy pensando en esta línea de acciones. – user1366786

+0

Via Groovy a continuación es el enlace. http://stackoverflow.com/questions/38972221/api-automation-groovy-soapui-all-together-for-most/38974183#38974183 –

Respuesta

18

lo general el uso Cucumber a prueba mis API de descanso. El siguiente ejemplo está en Ruby, pero podría traducirse fácilmente a python utilizando the rubypy gem o lettuce.

de inicio con una serie de pasos básicos REST:

When /^I send a GET request for "([^\"]*)"$/ do |path| 
    get path 
end 

When /^I send a POST request to "([^\"]*)" with the following:$/ do |path, body| 
    post path, body 
end 

When /^I send a PUT request to "([^\"]*)" with the following:$/ do |path, body| 
    put path, body 
end 

When /^I send a DELETE request to "([^\"]*)"$/ do |path| 
    delete path 
end 

Then /^the response should be "([^\"]*)"$/ do |status| 
    last_response.status.should == status.to_i 
end 

Then /^the response JSON should be:$/ do |body| 
    JSON.parse(last_response.body).should == JSON.parse(body) 
end 

Y ahora podemos escribir características que ponen a prueba la API mediante la emisión de hecho las solicitudes.

Feature: The users endpoints 

    Scenario: Creating a user 
    When I send a POST request to "/users" with the following: 
     """ 
     { "name": "Swift", "status": "awesome" } 
     """ 
    Then the response should be "200" 

    Scenario: Listing users 
    Given I send a POST request to "/users" with the following: 
     """ 
     { "name": "Swift", "status": "awesome" } 
     """ 
    When I send a GET request for "/users" 
    Then the response should be "200" 
    And the response JSON should be: 
     """ 
     [{ "name": "Swift", "status": "awesome" }] 
     """ 

    ... etc ... 

Estos son fáciles de ejecutar en un sistema de CI de su elección. Ver estos enlaces para referencias:

+2

Gracias Swift. Seguiré tu ejemplo. – user1366786

+1

No hay problema, me alegro de poder ayudar – Swift

1
import openpyxl 
import requests 
import json 
from requests.auth import HTTPBasicAuth 

urlHead='https://IP_ADDRESS_HOST:PORT_NUMBER/' 

rowStartAt=2 
apiColumn=2 
#payloadColumn=3 
responseBodyColumn=12 
statusCodeColumn=13 

headerTypes = {'Content-Type':'application/json', 
       'Accept':'application/json', 
       'Authorization': '23324' 
       } 

wb = openpyxl.load_workbook('Excel_WORKBOOK.xlsx') 

# PROCESS EACH SHEET 
for sheetName in (wb.get_sheet_names()): 
    print ('Sheet Name = ' + sheetName) 

    flagVar = input('Enter N To avoid APIs Sheets') 
    if (flagVar=='N'): 
     print ('Sheet got skipped') 
     continue 


    #get a sheet 
    sheetObj = wb.get_sheet_by_name(sheetName) 

    #for each sheet iterate the API's 
    for i in range(2, sheetObj.max_row+1): 
     #below is API with method type 
     apiFromSheet = (sheetObj.cell(row=i, column=apiColumn).value) 
     if apiFromSheet is None: 
      continue 

     #print (i, apiFromSheet) 
     #Let's split the api 
     apiType = apiFromSheet.split()[0] 
     method = apiFromSheet.split()[1] 

     if (apiType!='GET'): 
      continue 

     #lets process GET API's 
     absPath = urlHead + method 
     print ("REQUESTED TYPE AND PATH = ", apiType, absPath) 
     print('\n') 


     res = requests.get(absPath, auth=HTTPBasicAuth(user, pwd),   verify=False, headers=headerTypes) 

     #LET's write res body into relevant cell 
     sheetObj.cell(row=i, column=responseBodyColumn).value = (res.text) 
     sheetObj.cell(row=i, column=statusCodeColumn).value = (res.status_code) 
     wb.save('Excel_WORKBOOK.xlsx') 



      `#exit(0)` 
Cuestiones relacionadas