Sobes.tech
Junior

How to check if fields are in the correct order?

sobes.tech AI

Answer from AI

  • Manually: Visual verification of the interface according to designs or specifications.
  • Automated:
    • UI testing: Obtaining the order of elements (fields) using locators and comparing with the expected list.
    • API testing: Checking the order of fields in JSON/XML responses (especially relevant for serialization/deserialization of API data). Parsing the response and iterating over keys/elements in the expected order.
    • Database testing: Checking the order of columns in a table (although less common for logical order of fields in the user interface or API).
# Example in Python using Selenium WebDriver to check the order of elements on a web page

from selenium import webdriver

driver = webdriver.Chrome() # Use the appropriate driver

try:
    driver.get("https://example.com/form") # URL of the page with the form

    # Expected order of fields (locators)
    expected_order = [
        "id_username",
        "id_password",
        "id_email",
    ]

    actual_order_elements = driver.find_elements_by_css_selector(".form-field") # Example CSS selector for fields

    actual_order_ids = [element.get_attribute("id") for element in actual_order_elements]

    # Compare the actual order with the expected
    assert actual_order_ids == expected_order, f"Incorrect order of fields. Expected: {expected_order}, Actual: {actual_order_ids}"

    print("The order of fields is correct.")

except Exception as e:
    print(f"Error checking the order of fields: {e}")

finally:
    driver.quit()

// Example in Java using JUnit and Rest Assured to check the order of fields in an API JSON response

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class ApiOrderTest {

    @Test
    public void testFieldOrderInApiResponse() {
        RestAssured.baseURI = "https://api.example.com"; // Base URL of the API

        Response response = given()
                .when()
                .get("/users/1") // Endpoint returning user data
                .then()
                .statusCode(200)
                .extract().response();

        // Extract keys from the JSON response
        List<String> actualKeys = response.jsonPath().getMap("$").keySet().stream().toList();

        // Expected order of keys
        List<String> expectedKeys = Arrays.asList("id", "username", "email", "created_at");

        // Compare the actual order with the expected
        assertEquals(expectedKeys, actualKeys, "Incorrect order of fields in JSON response.");

        System.out.println("The order of fields in the JSON response is correct.");
    }
}

How to check if fields are in the correct order? — QA… - sobes.tech