Versiones comparadas

Clave

  • Se ha añadido esta línea.
  • Se ha eliminado esta línea.
  • El formato se ha cambiado.

...

  • PATH PARAMETERS

    • Es la continuidad de la ruta de una URL (parámetros separados por “/”)

      • Normalmente son la información REQUERIDA de una URL para un Post.

      • Siempre van primero antes de los Query Parameters

      • Postman puede detectar estos Path con la key “:” para colocar el valor Path Parameter:
        Ejemplo:

  • QUERY PARAMETERS (QP)

    • Son los campos específicos de un body
      (parámetros comenzados por un “?” y separados por “&” en la URL)

    • Normalmente son información opcional de una URL para hacer un Post, PERO algunos Query Parameters son OBLIGATORIOS.

    • Siempre van después del “?”

COMPONENTES DE POSTMAN PARA PRUEBAS API

EQUIVALENCIAS DE INCIDENCIAS QA
con el WORKFLOW de API Testing (con Postman)

...

 

SCRIPTS (AUTOMATION TESTING)

...

1. SINTAXIS DE LOS SCRIPTS DE PRUEBA:

  • En Postman, cada “test” es un Step del Caso de Prueba para validar.
    La sintaxis inicial es siempre la misma:

    • Bloque de código
      pm.test("Descripción del Step de Prueba", function() {});
  • En cada SCRIPT siempre debe haber una “Assertion”, y a veces una “Variable” para hacer el Test.
    Como en el ejemplo siguiente, un Assertion:

    • Bloque de código
      pm.test("validar codigo 200", function () {
          pm.response.to.have.status(200);
      });

      El Assertion era:

      Bloque de código
      pm.response.to.have.status();

      Hay demasiados tipos de “Assertion” que se pueden usar (véase: https://www.chaijs.com/api/bdd/)

    • En caso de una Variable de Script, el ejemplo visual es el siguiente:

      Bloque de código
      const jsonData = pm.response.json();

      Se puede usar la declaración de variable dentro del bloque de código del test o fuera del mismo:

      Bloque de código
      const jsonData = pm.response.json();
      pm.test("Validar status de protocolo https", function() {
          pm.expect(jsonData.name).to.eql("TV Samsung 123");
      });
      pm.test("Validar status de protocolo https", function() {
          const jsonData = pm.response.json();
          pm.expect(jsonData.name).to.eql("3er Created by API");
      });

      (En el ejemplo arriba se usó un Script para testear “Parámetros” del JSON recibido)

      (Se recomienda siempre usar “const” para declarar una variable que será inmutable)
      (En caso de que, por alguna razón, la variable será duplicada en el mismo script, se usa “let”)

  • IMPORTANTE A TOMAR EN CUENTA:
    → QUÉ VARIABLE DECLARAR EN LOS SCRIPTS: (Diferencia entre VAR vs LET vs CONST)

    https://youtu.be/bvkY9ey83yY

  • RECOMENDACIÓN:
    USAR SIEMPRE → “Console.log()” para poder ver y chequear los datos de los Objetos del Body antes de poder hacer los ASSERTIONS.

...

...

 

2. SCRIPTS para PARAMETERS:

...

  • Los Assertions SIEMPRE van a estar en un Script de Prueba.

  • Para VALIDAR un resultado esperado, se deben usar Assertions SEGÚN EL BODY DE RESPUESTA DEL API.

    • Cada Software tiene su estructura de código presentada con sus API, las cuales pueden ser variadas, aunque la más común hoy en día es la de JSON por su adaptabilidad a cualquier lenguaje como todos sabemos.

  • A continuación se presentará cada SINTAXIS para HACER SCRIPTS SEGÚN EL “RESPONSE BODY”:

    • JSON →→ 🚩

      • Bloque de código
        pm.response.json()
    • XML →

      • Bloque de código
        xml2Json(responseBody)
    • HTML →

      • Bloque de código
        cheerio(pm.response.text())
    • Plain-Text →

      • Bloque de código
        pm.response.text()
    • CSV →

      • Bloque de código
        csv-parse/lib/sync
  • CHAI ASSERTION LIBRARY:

  • QUIZ DE ASSERTIONS PARA LA CLASE: (COPIA Y PEGA EN EL SCRIPT para que aprecies el código.

    • DELIVERY QUIZ:
      ENVÍA LA RESPUESTA AL PRIVADO Y TE DIRÉ TU PUNTUACIÓN

    • Bloque de código
      // CHAI ASSERTIONS Quiz
      
      //Q1: 
      // De acuerdo a este Assertion de la documentación Chai
      expect(false).to.be.false;
      //Cómo puedes correr esto en Postman?
      //1
      expect(false).to.be.false
      //2
      pm.expect(false).to.be.false;
      //3*
      pm.test("Step", function(){
          pm.expect(false).to.be.false;
      });
      
      //Q2: 
      // Observa muy bien la siguiente Assertion dentro del test:
      pm.test("Step", function(){
          let number = '5';
          pm.expect(number).to.eql(5);
      //Cuál sería el Outcome de la prueba?
      //1
      //La prueba será PASS, porque 5 es igual a 5
      //2*
      //La prueba será FAIL, porque los dos valores tienen diferentes tipos de daata. '5' is un String y 5 is un número.
      
      //Q3: 
      // Considera el Assertion del siguiente Test:
      pm.test("Step", function(){
          let number;
          pm.expect(number).to.eql(null);
      //Cuál sería el Outcome de la prueba?
      //1*
      //La prueba será PASS, porque el número NO está definido, así que por predeterminado es NULL
      //2
      //La prueba será FAIL, porque el number NO está definido, y así NO es igual a NULL.
      
      //Q4: 
      // Quieres chequear un valor (netflix) en un Array de múltiples valores (youtube,netflix,twitch). Cómo lo harías?
      //1
      pm.test("Step", function(){
          pm.expect('netflix').to.eql(['youtube','netflix','twitch']);
      });
      //2*
      pm.test("Step", function(){
          pm.expect('netflix').to.be.oneOf(['youtube','netflix','twitch']);
      });
      //3
      pm.test("Step", function(){
          pm.expect(netflix).to.be.oneOf([youtube,netflix,twitch]);
      });
      //4
      pm.test("Step", function(){
          pm.expect('netflix').to.be.eql('youtube');
          pm.expect('netflix').to.be.eql('netflix');
          pm.expect('netflix').to.be.eql('twitch');
      });

ASSERTIONS SCRIPTS en ARRAYS

...

  • Para validar un Parámetro (Key-Valor) QUE SE ENCUENTRA DENTRO DE UN ARRAY de un Body de JSON,
    Se necesita usar los Corchetes “[]” para iterar y señalar el parámetro a validar:

    Bloque de código
    const Body = pm.response.json();
    const altura = Body[0].prefs.backgroundImageScaled[5];
    
    pm.test("Altura debería ser igual a 854", function(){
        pm.expect(altura.height).to.eql(854);
    });

    Aquí se hizo primero un script para encontrar un Parámetro DENTRO de un Array (backgroundImageScaled[5]), cuyo array se encuentra DENTRO de otro Array (“Body[0].prefs”) el cual se encuentra DENTRO del Body del Json (por eso se usa el “pm.response.json();” para definir el cuerpo del JSON y convertirlo en variable “Body”, para luego combinárlo con el otro script y convertirlo en la variable “altura” en este caso.
    Luego de tener la ubicación del parámetro, se aplica el Scrit de Test para validar como siempre.

  • AHORA: Para validar un Parámetro QUE NO SE SABE DÓNDE SE ENCUENTRA EL MISMO EN EL ARRAY,
    Entonces en lugar de usar Corchetes “[]” se puede usar una función “For” para ITERAR y encontrarlo:

    Bloque de código
    const Body = pm.response.json();
    let altura; //Aquí se usa "let" porque aún no se define la variable (si no, sale error)
    for (const image of Body.backgroundImageScaled){
        if (image.width == 2048) {
            altura = image; //Aquí mismo se define la variable y está disponible
        };
    };
    pm.test("Ancho debería ser igual a 2048", function(){
        pm.expect(altura.width).to.eql(2048);
    });

SCRIPT PODEROSO PARA ENCONTRAR CUALQUIER PROPIEDAD!
Usando el Chai Assertion: “.find(Objeto => Objeto.atributo === “valor”)”

Ejemplo:

...

Donde “i” es una auto-variable que está refiriéndose a TODA LA ARRAY como un “item”, y que a su vez está diciendo que la llave (atributo) debe ser exactamente igual al valor (valor de la propiedad). Y lo que hará es BUSCAR TODOS LOS MISMOS ATRIBUTOS pero se detendrá cuando encuentre el valor declarado.

PLUS: SCRIPTS CON CARACTERES ESPECIALES

  • Cuando se tiene “CARATERES ESPECIALES” dentro de una Propiedad, ya no se puede usar el mismo object notation “ object.object.object “, sino que se debería usar los Corchetes “[]” encerrando la palabra junto con las comillas. Ejemplo:

    • Bloque de código
      languagejs
      console.log(Body.object.object-caracter); 
      // Body siendo el Json response, y "objeto-caracter" es un objeto dentro de "object".
      // En este escenario, estaría mal escrito porque un atributo tiene "-" como símbolo.
      // Cualquier símbolo en esta posición no puede ser leído de esta manera.
      
      console.log(Body.object["object-caracter"]);
      //En este escenario, SÍ estaría correcto, para poder aceptar caracteres especiales.
      

5. ASSERTIONS SCRIPTS para HEADERS y COOKIES

  • Además de Scripts para Status Code, Scope Parameters y Response Body, también hay para:
    HEADERS y COOKIES.

    • HEADERS:
      Así se realiza un script para obtener un header desde el Response: (ejemplo)

      • Bloque de código
        languagejs
        pm.responsse.headers.get('X-Cache')

        En un Test:

        • Si existe el Header:

          Bloque de código
          languagejs
          pm.response.to.have.header('X-Cache');
        • Si el Header tiene un cierto valor:

          Bloque de código
          languagejs
          pm.expect(pm.response.headers.get('X-Cache')).to.eql('HIT');
    • COOKIES:
      Similar al anterior, así se realiza el script para obtener las cookies: (ejemplo)

      • En un Test:

        • Si existe las Cookies:

          Bloque de código
          languagejs
          pm.expect(pm.cookies.has('sessionId')).to.be.true; 
        • Si el Cookies tiene un cierto valor:

        • Bloque de código
          languagejs
          pm.expect(pm.cookies.get('sessionId')).to.eql(’ad3se3ss8sg7sg3'); 

           

 

Sugerencia

MÁS EJEMPLOS DE TEST SCRIPTING:

https://learning.postman.com/docs/writing-scripts/script-references/test-examples/

...

Assertion deep equality error

You may encounter the AssertionError: expected <value> to deeply equal '<value>'. For example, this would arise with the following code:

Bloque de código
languagejs
pm.expect(1).to.eql("1");

This happens because the test is comparing a number to a string value. The test will only return true if both the type and value are equal.

Asserting the current environment

Check the active (currently selected) environment in Postman:

Bloque de código
languagejs
pm.test("Check the active environment", () => {
  pm.expect(pm.environment.name).to.eql("Production");
});

JSON not defined error

You may encounter the ReferenceError: jsonData is not defined issue. This typically happens when you are attempting to reference a JSON object that hasn't been declared or is outside the scope of your test code.

Bloque de código
languagejs
pm.test("Test 1", () => {
  const jsonData = pm.response.json();
  pm.expect(jsonData.name).to.eql("John");
});

pm.test("Test 2", () => {
  pm.expect(jsonData.age).to.eql(29); // jsonData is not defined
});

Make sure that any code setting your response data to a variable is accessible to all test code, for example in this case moving const jsonData = pm.response.json(); before the first pm.test would make it available to both test functions.

Asserting a value type

Test the type of any part of the response:

Bloque de código
languagejs
/* response has this structure:
{
  "name": "Jane",
  "age": 29,
  "hobbies": [
    "skating",
    "painting"
  ],
  "email": null
}
*/
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
  pm.expect(jsonData).to.be.an("object");
  pm.expect(jsonData.name).to.be.a("string");
  pm.expect(jsonData.age).to.be.a("number");
  pm.expect(jsonData.hobbies).to.be.an("array");
  pm.expect(jsonData.website).to.be.undefined;
  pm.expect(jsonData.email).to.be.null;
});

Asserting array properties

Check if an array is empty, and if it contains particular items:

Bloque de código
languagejs
/*
response has this structure:
{
  "errors": [],
  "areas": [ "goods", "services" ],
  "settings": [
    {
      "type": "notification",
      "detail": [ "email", "sms" ]
    },
    {
      "type": "visual",
      "detail": [ "light", "large" ]
    }
  ]
}
*/

const jsonData = pm.response.json();
pm.test("Test array properties", () => {
    //errors array is empty
  pm.expect(jsonData.errors).to.be.empty;
    //areas includes "goods"
  pm.expect(jsonData.areas).to.include("goods");
    //get the notification settings object
  const notificationSettings = jsonData.settings.find
      (m => m.type === "notification");
  pm.expect(notificationSettings)
    .to.be.an("object", "Could not find the setting");
    //detail array should include "sms"
  pm.expect(notificationSettings.detail).to.include("sms");
    //detail array should include all listed
  pm.expect(notificationSettings.detail)
    .to.have.members(["email", "sms"]);
});

Asserting object properties

Assert that an object contains keys or properties:

Bloque de código
languagejs
pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b');
pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd');
pm.expect({a: 1}).to.have.property('a');
pm.expect({a: 1, b: 2}).to.be.an('object')
  .that.has.all.keys('a', 'b');

Target can be an object, set, array or map. If .keys is run without .all or .any, the expression defaults to .all. As .keys behavior varies based on the target type, it's recommended to check the type before using .keys with .a.

Asserting that an object is contained

Check that an object is part of a parent object:

Bloque de código
languagejs
/*
response has the following structure:
{
  "id": "d8893057-3e91-4cdd-a36f-a0af460b6373",
  "created": true,
  "errors": []
}
*/

pm.test("Object is contained", () => {
  const expectedObject = {
    "created": true,
    "errors": []
  };
  pm.expect(pm.response.json()).to.deep.include(expectedObject);
});

Using .deep causes all .equal, .include, .members, .keys, and .property assertions that follow in the chain to use deep equality (loose equality) instead of strict (===) equality. While the .eql also compares loosely, .deep.equal causes deep equality comparisons to also be used for any other assertions that follow in the chain, while .eql doesn't.

 

Sugerencia

AUTOMATION API TESTING🚀 CON COLLECTIONS

Corriendo una Collection Enorme Automatizada desde Postman:

...

Corriendo una Collection CRUD Automatizada usando Newman desde la terminal:

...

((EL TEMARIO SERÁ SUBIDO LUEGO DEL JUEVES 5 DE MAYO))