Hi MD, if you like to do api and ui (browser) testing together you can include both Rest-assured and selenium lib in your project. I will check and plan on this
Here you took response and using convertor you have generate the schema but what If we don't have response then how we are generating the schema. Are we creating manually by own.
Vaishali If you don't have a response, there are a few options: 1. Manual Creation: You can manually create the schema based on the API documentation or your knowledge of the expected response structure. This can be time-consuming and error-prone, especially for complex APIs. 2. Mock Responses: If possible, you can use a mock server or a similar tool to simulate the API responses. You can then generate the schema from these mock responses. 3. API Documentation: If the API follows specifications like OpenAPI (formerly Swagger), the schema might be available in the API documentation itself. Remember, the purpose of the schema is to validate the structure of the API response. So, it needs to accurately represent the expected response structure for your tests to be meaningful. If the schema is incorrect or incomplete, your tests might pass when they shouldn't, or fail when they shouldn't ..
Hi Raghav bro, Thanks for your tutorials which helps me lot to improvise my skillsets. I've a doubt in Json Schema validation. In real time, we have multiple schema for each API, so do we need to create n number of schema.json under target folder with different names?? Also it's preferable/ gud practice method to validate the real time get api in frame work ? I'm gonna execute API automation in my project, so pls suggest me your valuable feedbacks.
Hi Prakash, you can add multiple schemas as needed and point to the right schema during validation. The good practice is only that your test/validation should be generic in the sense that it should be able to validate the api with diff values and data, Rest all depends on your needs for testing
Hi Raghav, Thank you for sharing your knowledge extensively in a calm understandable manner. I have been trying to use the POJO class inorder to generate json body to the Request Payload. But this looks tedious on multi level nested jsons, is there a way or library available, which can consider the json template and populate the data from either a csv file or xls . I tried to check online but couldnt get much info. Ex: consider below as the template, with $variables could directly be replaced { "names":["firstname": "$fname", "lastname":"$lname"], "personal":["Occup":{ "occ1":"$occvalue","occ2":"$occvalue2" }] } csv file has fname,lname,occvalue,occvalue2 etc Raghav,Pal,value2,value3 James,Jim,value4,value5
John Handling multi-level nested JSON structures and populating them with data from CSV or Excel files can be achieved using various tools and libraries. Let's explore some options: 1. Custom Scripting (Python, JavaScript, etc.): - You can write custom scripts to read data from a CSV file and dynamically replace placeholders in your JSON template. - For Python, you can use the `csv` module to read the CSV file and then format your JSON accordingly. - Similarly, in JavaScript, you can use libraries like `csv-parser` to parse CSV data and create the desired JSON structure. 2. Excel Add-ins (Microsoft Excel): - If you're working with Excel files, consider using Excel add-ins or macros. - You can create an Excel template with placeholders and use VBA (Visual Basic for Applications) macros to populate the data from a CSV file into the template. - This approach allows you to leverage Excel's built-in features for data manipulation. 3. Third-Party Libraries: - There are libraries available that simplify this process: - xlsx-populate (JavaScript): - This library allows you to read and modify Excel files (XLSX format) directly from JavaScript. - You can load an existing Excel template, replace placeholders, and save the modified file. - Plumsail Documents Connector (Power Automate): - Use the "Parse CSV" action from the Plumsail Documents connector to convert CSV data into an Excel table. - Then, populate the Excel table with the desired data. Remember to choose the approach that best fits your requirements and the tools you're comfortable with
Hi Raghav, thanks for creating a series of simple and effective tutorials. I have a question, How can I execute services that require anonymous or password-type tokens.
Hi Raghav, Thank you for this video. I am able to do schema validation as you explained in video. However, one of the API schema which I am working on, contains NaN value. I am not able to do schema validation due to NaN values. Please advise on how to resolve this issue.
Thanks as always for your great tutorials. I am trying to do something maybe too easy but I am stuck. Basically, I want to assert a complete file.json but I don't know how. It's a long JSON file and it's not going to change (hope so). Do you know how to that? thanks in advance!
Hi, this can help medium.com/@iamfaisalkhatri/how-to-perform-json-schema-validation-using-rest-assured-64c3b6616a91 dzone.com/articles/structural-validation-of-json-response-using-rest
Priyanka Here are some popular libraries for JSON validation in TypeScript projects: 1. Ajv: A powerful JSON schema validator that supports TypeScript. It provides utility types like `JSONSchemaType` to simplify writing schemas ```bash npm install ajv ``` ```typescript import Ajv, { JSONSchemaType } from "ajv"; const ajv = new Ajv(); const schema: JSONSchemaType = { /* schema definition */ }; const validate = ajv.compile(schema); const valid = validate(data); ``` 2. ts-json-validator: This library allows you to define JSON schemas and TypeScript types in one place, ensuring they stay in sync ```bash npm install ts-json-validator ``` ```typescript import { createSchema as S, TsjsonParser } from "ts-json-validator"; const parser = new TsjsonParser( S({ type: "object", properties: { a: S({ type: "string" }), b: S({ type: "number" }), c: S({ type: "string", enum: ["B1", "B2"] as const }) }, required: ["a"] }) ); const valid = parser.parse(data); ``` 3. typeofweb/schema: A lightweight and extensible library for data validation with full TypeScript support ```bash npm install @typeofweb/schema ``` ```typescript import { object, string, number } from "@typeofweb/schema"; const schema = object({ a: string(), b: number().optional(), c: string().enum("B1", "B2").optional() }); const valid = schema.validate(data); ``` These libraries should help you ensure your API responses are correctly validated in your TypeScript projects -
Praveen Yes, you can often reuse the same JSON schema validation script for both console apps and other environments, as long as it's written in a language that's compatible with your console app development framework. Here's a general approach: 1. Choose a JSON Schema Validation Library: - Select a library that supports your chosen programming language and offers robust validation features. Popular options include: - JavaScript: Ajv, tv4, jsonschema - Python: jsonschema - Java: json-schema-validator - C#: Newtonsoft.Json.Schema - And many more for various languages 2. Load the Schema and JSON Data: - Load the JSON schema from a file or string using the library's methods. - Load the JSON data you want to validate similarly. 3. Perform Validation: - Call the validation function provided by the library, passing the schema and data as arguments. - The function will typically return a result indicating whether the data is valid or not, along with any validation errors encountered. 4. Handle Results: - If validation succeeds, proceed with further processing of the JSON data. - If validation fails, handle the errors appropriately, such as: - Displaying error messages to the user - Logging errors for debugging - Terminating the application if necessary Console App Considerations: - Input/Output: Use appropriate console input/output methods to read the schema and data files, and display validation results. - Error Handling: Implement robust error handling to catch exceptions and provide meaningful feedback to the user. - Library Integration: Ensure the chosen validation library is compatible with your console app's development environment and dependencies. Example (Python): ```python import json from jsonschema import validate # Load schema and data with open("schema.json") as f: schema = json.load(f) with open("data.json") as f: instance = json.load(f) # Validate try: validate(instance, schema) print("JSON data is valid!") except jsonschema.ValidationError as e: print("JSON data is invalid:", e) ``` Key Points: - Reusability: JSON schema validation scripts are often reusable across different environments. - Library Choice: Select a library that aligns with your programming language and requirements. - Error Handling: Implement robust error handling for user-friendly validation feedback.
Bhuvaneswari There are two ways to handle a 30-line request body in a POST request using Rest Assured: 1. *Use a string:* You can simply pass the request body as a string to the `body()` method. For example: ```java String requestBody = """ { "name": "John Doe", "age": 30, "occupation": "Software Engineer", ... } """; given() .contentType(ContentType.JSON) .body(requestBody) .when() .post("/users"); ``` 2. *Use a file:* If the request body is very large or complex, you can store it in a file and then pass the file to the `body()` method. For example: ```java File requestBodyFile = new File("request_body.json"); given() .contentType(ContentType.JSON) .body(requestBodyFile) .when() .post("/users"); ``` Which method you choose depends on your specific needs. If the request body is relatively small and simple, then you can simply pass it as a string. If the request body is very large or complex, then you should store it in a file and then pass the file to the `body()` method. Here are some additional tips for handling a 30-line request body in a POST request using Rest Assured: * Use a JSON parser to parse the request body into a JSON object. This can be useful for validating the request body or for extracting data from the request body. * Use a string builder to build the request body. This can be useful for creating a complex request body from multiple parts. * Use a file reader to read the request body from a file. This can be useful for handling very large request bodies. I hope this helps
Hi Raghav !!! can we get a tutorial on API Testing with the BDD framework .....means using feature files, step definition files, and runner files, and all.............the kind-hearted is for your reply
Hello Raghav, I have a query.. in my automation, while testing we use device, and test report on web page. Is there any way in selenium we can listen to my web app server where device sending request/ respond
Hello Raghav I have a question ...how to learn protractor with javascript from the basic actually I don't know anything about coding and I already follow ur series but I am facing a lot issue.I mean according to my organization requirement I am not able to design script according to test case because I don't know anything about coding but my manager give the same task for everyone and I am facing so many problems plz help me. Like how to write scripts 😭
@Anjali : For your information Protractor is going to deprecate in near future. My request is to please stop learning it if u plan to learn. Instead go with cypress
Hi Raghav - Sir I am getting the "Schema to use cannot be null" exception because the json file is getting auto-cleaned up / deleted from the target folder. How to fix this?
Rohit There are a few possible reasons why the JSON file might be getting deleted: * Eclipse's automatic build process might be cleaning up the target folder. * A plugin or feature in Eclipse might be configured to delete files in the target folder. * Your project's configuration or build script might be deleting the file. Step 1: Check Eclipse's build settings Check your Eclipse project's build settings to see if there's a configuration that's causing the file to be deleted. You can do this by: * Going to Project > Properties > Builders * Checking the "Clean" tab to see if there's a pattern that matches your JSON file * Checking the "Output Folder" tab to see if the target folder is being cleaned Step 2: Check for plugins or features Check if you have any plugins or features installed in Eclipse that might be causing the file deletion. You can do this by: * Going to Help > Eclipse Marketplace * Checking if you have any plugins installed that might be related to file cleanup or build processes Step 3: Check your project's configuration and build script Check your project's configuration files (e.g., pom.xml if you're using Maven) and build scripts to see if there's a configuration that's causing the file to be deleted. Step 4: Fix the issue Based on your findings, you can try one of the following solutions: * If Eclipse's build settings are causing the file deletion, update the settings to exclude the JSON file from the clean process. * If a plugin or feature is causing the file deletion, disable or uninstall the plugin. * If your project's configuration or build script is causing the file deletion, update the configuration to preserve the JSON file. Additional Tips: * Make sure the JSON file is in the correct location and is being copied to the target folder correctly. * Check if you're using a relative or absolute path to reference the JSON file in your Rest Assured tests. * Consider using a more robust way to manage your JSON schema files, such as storing them in a separate folder or using a schema management tool. -
Hi Raghav , i have a question but not related to this video , am doing selenium with java ui automation using testNg framework , now i gave demo to my manager by showing code in eclipse IDE and how it runs , but he wants the complete project as a single file and he needs to run from his machine . how can we achieve it ? as a layman he don't want to install eclipse or other required stuff , he needs to run with single command or click , like postman collection can be run thru newman run "url". so could you pls let me know how to achieve it. if we convert my project to jar can we run ?
Hi Raghav. I am facing some issues. I have added schema.json file into Target>>classes Folder but don't know why it is automatically gets removed from the target folder. Please help me.
Hi Prasad The `assureThat()` method is not a method of the `Response` class in Playwright. It is a method of the `expect` function, which is used to make assertions in Playwright tests. To assert something about a `Response` object, you can use the `expect` function with the `toEqual()` matcher. For example, the following code asserts that the status code of the `Response` object is 200: ``` const response = await page.request('example.com'); expect(response).toEqual({ status: 200, }); ``` The `assertThat()` method is a method of the `Assert` class in JUnit. If you are using JUnit to write your Playwright tests, you can use the `assertThat()` method to make assertions about `Response` objects. For example, the following code asserts that the status code of the `Response` object is 200: ``` import org.junit.Assert; public class MyTest { @Test public void testResponse() { const response = await page.request('example.com'); Assert.assertThat(response, Matchers.hasProperty("status", 200)); } } ``` I hope this helps
@@RaghavPal Hi Sir. Thanks for the detailed information. actually its my mistake I used "assertThat()" after "get()". That's why I was getting this error. But now it is showing another error "Schema to use cannot be null"
Hi Ali No, Rest-assured is a Java-based library for testing RESTful APIs, but it is not designed specifically for contract testing. Contract testing involves verifying that two communicating systems, such as a client and a server, adhere to an agreed-upon interface or contract. It ensures that changes made to one system do not break the other system's functionality. Rest-assured can be used to write tests that validate the functionality of RESTful APIs, which can be part of the overall contract testing process.
Yes, there are several open source tools available for contract testing, in addition to PACT. Here are a few options you can consider: Spring Cloud Contract: Spring Cloud Contract is an open source framework that allows you to write consumer-driven contract tests in Spring-based applications. It supports several messaging protocols and can generate stubs and tests for both the consumer and provider sides of the contract. Spring Cloud Contract also integrates with popular testing frameworks like JUnit and TestNG. Hoverfly: Hoverfly is an open source API simulation and testing tool that can be used for contract testing. It allows you to simulate API responses and generate contract tests automatically. It supports several languages and protocols and can be integrated with popular testing frameworks like JUnit and TestNG. Pactum: Pactum is a lightweight, open source contract testing library that can be used to test RESTful APIs. It supports both JSON and XML request and response payloads and can generate stubs and tests automatically. Pactum also integrates with popular testing frameworks like Mocha and Jest. Karate DSL: Karate DSL is an open source testing framework that can be used for contract testing. It supports both HTTP and HTTPS protocols and allows you to write tests in a simplified, English-like syntax. Karate DSL also provides built-in support for data-driven testing and can be integrated with popular CI/CD tools like Jenkins. These are just a few examples of open source contract testing tools available. The best tool for your needs depends on your specific requirements and preferences.
Before modifying the email field from string to integer and running the program, I got an error - Schema to use cannot be null. I resolved the issue by placing the schema.json file to src/test/folder
@@RaghavPal Hi Raghav. I am facing the same issue.. I have added schema.json file into Target>>classes Folder but don't know why it is automatically gets removed from the target folder. I've also tried to put it into src/test folder but the same issue is occurred. Please help me.
Hi Daniel, sometimes it is required and also a good practice to check your json is as per the schema, that defines the structure and format of the json, This will help you further - ua-cam.com/play/PLhW3qG5bs-L992N-g4IgeNirZ1KY5WrkO.html
Jaimin While I don't have access to the specific query responses and ratings you mentioned, I can provide general guidance and potential solutions based on common causes of this error: Understanding the Error: - This error usually indicates that Rest Assured is unable to locate or access the JSON schema file you're trying to use for validation. - Double-check that you've provided the correct file path or schema object to the relevant validation methods. Troubleshooting Steps: 1. Verify Schema Path: - Ensure the path you're specifying in your code points to the exact location of the schema file relative to your project directory. - If it's an external URL, confirm that the URL is reachable and doesn't require authentication. - Consider using absolute paths or classpath-relative paths for clarity. 2. Inspect Schema Content: - Make sure the schema file is valid JSON and doesn't contain syntax errors. Use JSON validators or linters to check for issues. - Verify that the schema structure aligns with the expected response from the API endpoint you're testing. 3. Check Schema Object Construction: - If you're building the schema dynamically, ensure you're using the correct methods and providing valid data according to Rest Assured's schema API. - Double-check for typos or incorrect values in your schema construction code. 4. Handle Null Schemas: - If the schema might be null in certain scenarios, implement logic to handle that gracefully. You could conditionally apply validation or provide a default behavior. 5. Consider Other Possibilities: - If the above steps don't resolve the issue, provide more context about your test code, schema location, and the specific method you're using for validation. - Check for compatibility issues between your Rest Assured version and any external libraries you're using for schema handling. Code Example (Basic Case): ```java import static io.restassured.module.jsonschema.JsonSchemaValidator.*; // Assuming you have a valid JSON schema file named "schema.json" in your project's resources directory String schemaPath = "classpath:schema.json"; given() ./* other request setup */ .when() .get(/* your API endpoint */) .then() .assertThat() .body(matchesJsonSchemaInClasspath(schemaPath)); ``` I hope this helps..
Hi sir, I'm facing one challenge. The challenge is " Copy the session ID value from cookies field in the the first user and paste the same session ID value in the second user and now send the request in postman expected response "401 unauthorized" how to automate this question on rest assured" ?
Hi Mahesh Here is the code to automate the challenge on Rest Assured: ``` import org.hamcrest.Matchers; import org.testng.annotations.Test; public class RestAssuredChallengeTest { @Test public void testUnauthorizedAccess() { // Get the session ID from the first user String sessionId = getSessionIdFromFirstUser(); // Try to access the resource with the session ID from the first user given() .cookie("sessionId", sessionId) .when() .get("/resource") .then() .statusCode(401); } private String getSessionIdFromFirstUser() { // Get the response from the first user Response response = given() .when() .get("/resource"); // Get the session ID from the cookies return response.cookies().get("sessionId"); } } ``` This code will first get the session ID from the first user. Then, it will try to access the resource with the session ID from the first user. Finally, it will check the status code of the response, which should be 401. To run this code, you will need to have Rest Assured installed. You can install Rest Assured using the following command: ``` mvn install org.rest-assured:rest-assured:latest ``` Once you have installed Rest Assured, you can run the code by running the following command: ``` mvn test ``` This will run the test and print the results to the console. If the test passes, you will see the following output: [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.036 s - in RestAssuredChallengeTest If the test fails, you will see the following output: [ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.036 s - in RestAssuredChallengeTest The error message will tell you why the test failed.
@raghav when trying to import getting error. import static io.restassured.module.jsv.JSONSchemaValidator.matchesJSONSchemaInClasspath; what could be the reason? java: package io.restassured.module.jsv does not exist
Andy The error you're encountering suggests that the io.restassured.module.jsv package is not found. This package is part of the Rest Assured library, specifically for JSON schema validation One possible reason for this issue is that you might be missing the necessary dependency in your project's pom.xml file. You need to include the following dependency to use JSON schema validation: com.jayway.restassured json-schema-validator 2.1.0 Make sure to add this dependency to your project's pom.xml file and try importing the JSONSchemaValidator class again Another possible reason could be that you're using an older version of Rest Assured that doesn't have the io.restassured.module.jsv package. You can try updating your Rest Assured version to the latest one -
Afwan The error message you're encountering-"java.lang.IllegalArgumentException: Schema to use cannot be null"-indicates that the schema you're trying to use for JSON validation is null. Let's troubleshoot this issue: 1. Check Your Schema File: - Ensure that the JSON schema file you're using for validation exists and is accessible. - Verify that the file path is correct and that the schema content is valid. 2. Use Correct Schema Path: - When using `matchesJsonSchemaInClasspath`, make sure the schema file is in the correct location relative to your classpath. - The schema file should be in the `src/test/resources` directory (or a subdirectory within it). - Example: ```java .body(matchesJsonSchemaInClasspath("schemas/my-schema.json")) ``` 3. Check for Null Values: - If you're dynamically loading the schema content, ensure that it's not null. - Double-check any logic that sets the schema content. 4. Verify Dependencies: - Make sure you have the necessary dependencies for JSON schema validation. - Ensure that you're using the correct version of the library (e.g., `io.rest-assured:json-schema-validator`). 5. Test with a Simple Schema: - Temporarily use a simple schema (even an empty one) to see if the issue persists. - If it works with a basic schema, gradually add complexity to your schema. 6. Inspect Your Test Code: - Review your test code to ensure that you're correctly invoking the schema validation. - Check if there are any null assignments or missing steps. 7. Update Dependencies: - If you're using an older version of Rest Assured or its dependencies, consider updating to the latest version. Remember to adapt these steps based on your specific project structure and requirements .
Joseph Let's break down the problem step by step. Problem: The error indicates that the schema to use is null, which is not allowed. Possible Causes: 1. Missing or invalid schema configuration: Rest Assured uses a schema to validate the response. If the schema is not provided or is invalid, it will throw this error. 2. Incorrect usage of `given()` or `expect()` methods: The `given()` and `expect()` methods in Rest Assured are used to specify the request and response specifications, respectively. If these methods are not used correctly, it can lead to this error. Step-by-Step Solution: 1. Check your Rest Assured configuration: Make sure you have properly configured Rest Assured to use a schema. You can do this by specifying the schema using the `schema` method or by providing a JSON schema file. Example: ```java RestAssured.config = RestAssured.config().schemaConfig(new SchemaConfig().with().mimeTypes("application/json", "json")); ``` 2. Verify your request specification: Check that you are using the `given()` method correctly to specify the request details. Example: ```java given() .header("Content-Type", "application/json") .body(requestBody) .when() .post("/api endpoint"); ``` 3. Verify your response specification: Check that you are using the `expect()` method correctly to specify the response details. Example: ```java expect() .statusCode(200) .body("key", equalTo("value")); ``` 4. Check for null values: Ensure that you are not passing null values to the `given()` or `expect()` methods. Example: ```java // Avoid this: given().body(null); // Instead, use an empty string or a valid request body: given().body(""); ``` 5. Review your JSON schema file (if using): If you are using a JSON schema file, ensure that it is valid and correctly configured. Example: ```java // schema.json file: { "$schema": "json-schema.org/draft-04/schema#", "type": "object", "properties": { "key": {"type": "string"} } } ``` By following these steps, you should be able to identify and fix the issue -
Raghav is Saint of Test automation.. Personally he is a awesome human being
Thanks for your kind words Krishna.. humbled
Your voice is so calming brother , I came here stressed and found everything is do-able 😇
so humbled and Glad to hear that
awesome Raghav, very nice explanation. Thank you so much.
You're most welcome
Thank you so much for this tutorial, Raghav
Glad it was helpful!
Sir, you are awesome! Thank you for this great tutorial!
You're very welcome!
Si JSONSchema Validated sucessfully...Thank you...
You are welcome Manish
Raghav could you please record a video of HOW to combine using REST Assure with UI?
Hi MD, if you like to do api and ui (browser) testing together you can include both Rest-assured and selenium lib in your project. I will check and plan on this
Hi Raghav please share the link if you have already created the integration betn rest assured with ui . Thanks in advance
Thanks Raghav sir...Nice Session
Most welcome Ayyappa
very good tutorial dear. Keep up the good work.
Thanks Rajiv
Hi Ragav,
The local host api section really helpful to practice... Thanks for the video
Most welcome
Hi, great stuff.
Hey, thanks Franco
very helpful, good Job!
Thanks
Thanks for wonderful video explaining very simply.
In JMeter, this can be done using this Plugin, "ApacheJmeter Schema Assertion", right?
Pankaj
Yes, you're on the right track.. To validate JSON Schema in JMeter, you can use the "ApacheJmeter Schema Assertion" plugin..
Here you took response and using convertor you have generate the schema but what If we don't have response then how we are generating the schema. Are we creating manually by own.
Vaishali
If you don't have a response, there are a few options:
1. Manual Creation: You can manually create the schema based on the API documentation or your knowledge of the expected response structure. This can be time-consuming and error-prone, especially for complex APIs.
2. Mock Responses: If possible, you can use a mock server or a similar tool to simulate the API responses. You can then generate the schema from these mock responses.
3. API Documentation: If the API follows specifications like OpenAPI (formerly Swagger), the schema might be available in the API documentation itself.
Remember, the purpose of the schema is to validate the structure of the API response. So, it needs to accurately represent the expected response structure for your tests to be meaningful. If the schema is incorrect or incomplete, your tests might pass when they shouldn't, or fail when they shouldn't
..
Hi Raghav bro, Thanks for your tutorials which helps me lot to improvise my skillsets. I've a doubt in Json Schema validation. In real time, we have multiple schema for each API, so do we need to create n number of schema.json under target folder with different names?? Also it's preferable/ gud practice method to validate the real time get api in frame work ? I'm gonna execute API automation in my project, so pls suggest me your valuable feedbacks.
Hi Prakash, you can add multiple schemas as needed and point to the right schema during validation.
The good practice is only that your test/validation should be generic in the sense that it should be able to validate the api with diff values and data, Rest all depends on your needs for testing
Hi Raghav,
Thank you for sharing your knowledge extensively in a calm understandable manner.
I have been trying to use the POJO class inorder to generate json body to the Request Payload.
But this looks tedious on multi level nested jsons, is there a way or library available, which can consider the json template and populate the data from either a csv file or xls . I tried to check online but couldnt get much info.
Ex: consider below as the template, with $variables could directly be replaced
{
"names":["firstname": "$fname", "lastname":"$lname"],
"personal":["Occup":{ "occ1":"$occvalue","occ2":"$occvalue2" }]
}
csv file has
fname,lname,occvalue,occvalue2 etc
Raghav,Pal,value2,value3
James,Jim,value4,value5
John
Handling multi-level nested JSON structures and populating them with data from CSV or Excel files can be achieved using various tools and libraries. Let's explore some options:
1. Custom Scripting (Python, JavaScript, etc.):
- You can write custom scripts to read data from a CSV file and dynamically replace placeholders in your JSON template.
- For Python, you can use the `csv` module to read the CSV file and then format your JSON accordingly.
- Similarly, in JavaScript, you can use libraries like `csv-parser` to parse CSV data and create the desired JSON structure.
2. Excel Add-ins (Microsoft Excel):
- If you're working with Excel files, consider using Excel add-ins or macros.
- You can create an Excel template with placeholders and use VBA (Visual Basic for Applications) macros to populate the data from a CSV file into the template.
- This approach allows you to leverage Excel's built-in features for data manipulation.
3. Third-Party Libraries:
- There are libraries available that simplify this process:
- xlsx-populate (JavaScript):
- This library allows you to read and modify Excel files (XLSX format) directly from JavaScript.
- You can load an existing Excel template, replace placeholders, and save the modified file.
- Plumsail Documents Connector (Power Automate):
- Use the "Parse CSV" action from the Plumsail Documents connector to convert CSV data into an Excel table.
- Then, populate the Excel table with the desired data.
Remember to choose the approach that best fits your requirements and the tools you're comfortable with
Hi Raghav, thanks for creating a series of simple and effective tutorials. I have a question, How can I execute services that require anonymous or password-type tokens.
Hi Anubhav, you can pass the tokens in the request, can see some examples on this
Thank you so much for this tutorial
You are so welcome Indhu
Very good explanation. One question. /target will get deleted when we use mvn clean ? Then how can we use schema valdiator ?
In a single session, it will work, we can check more on it
Hi Raghav, Thank you for this video. I am able to do schema validation as you explained in video. However, one of the API schema which I am working on, contains NaN value. I am not able to do schema validation due to NaN values. Please advise on how to resolve this issue.
Hi Swati, NaN means not a number, please check if in your schema it is expected to be a number and is not in the message
it was a great explanation but can we do soft assertions for validating json schema ? If yes how can we do that.
Hi Debanjan, not very sure if there is a direct way or annotation for that, will need to check online
Nice job. How we can achieve this if we are using a non-bdd script?
hi Ankit, what exactly do you mean, Rest assured used bdd syntax
Thanks as always for your great tutorials. I am trying to do something maybe too easy but I am stuck. Basically, I want to assert a complete file.json but I don't know how. It's a long JSON file and it's not going to change (hope so). Do you know how to that? thanks in advance!
Hi, this can help
medium.com/@iamfaisalkhatri/how-to-perform-json-schema-validation-using-rest-assured-64c3b6616a91
dzone.com/articles/structural-validation-of-json-response-using-rest
@@RaghavPal thank you so much master! I'll check it later
Hi sir ,
Can you suggest similar packages something for typescript projects
Priyanka
Here are some popular libraries for JSON validation in TypeScript projects:
1. Ajv: A powerful JSON schema validator that supports TypeScript. It provides utility types like `JSONSchemaType` to simplify writing schemas
```bash
npm install ajv
```
```typescript
import Ajv, { JSONSchemaType } from "ajv";
const ajv = new Ajv();
const schema: JSONSchemaType = { /* schema definition */ };
const validate = ajv.compile(schema);
const valid = validate(data);
```
2. ts-json-validator: This library allows you to define JSON schemas and TypeScript types in one place, ensuring they stay in sync
```bash
npm install ts-json-validator
```
```typescript
import { createSchema as S, TsjsonParser } from "ts-json-validator";
const parser = new TsjsonParser(
S({
type: "object",
properties: {
a: S({ type: "string" }),
b: S({ type: "number" }),
c: S({ type: "string", enum: ["B1", "B2"] as const })
},
required: ["a"]
})
);
const valid = parser.parse(data);
```
3. typeofweb/schema: A lightweight and extensible library for data validation with full TypeScript support
```bash
npm install @typeofweb/schema
```
```typescript
import { object, string, number } from "@typeofweb/schema";
const schema = object({
a: string(),
b: number().optional(),
c: string().enum("B1", "B2").optional()
});
const valid = schema.validate(data);
```
These libraries should help you ensure your API responses are correctly validated in your TypeScript projects
-
@@RaghavPal thank you sir
Hello Raghav,
Can we use the same script for the console apps? I have to validate the Schema with Json. Please help
Praveen
Yes, you can often reuse the same JSON schema validation script for both console apps and other environments, as long as it's written in a language that's compatible with your console app development framework. Here's a general approach:
1. Choose a JSON Schema Validation Library:
- Select a library that supports your chosen programming language and offers robust validation features. Popular options include:
- JavaScript: Ajv, tv4, jsonschema
- Python: jsonschema
- Java: json-schema-validator
- C#: Newtonsoft.Json.Schema
- And many more for various languages
2. Load the Schema and JSON Data:
- Load the JSON schema from a file or string using the library's methods.
- Load the JSON data you want to validate similarly.
3. Perform Validation:
- Call the validation function provided by the library, passing the schema and data as arguments.
- The function will typically return a result indicating whether the data is valid or not, along with any validation errors encountered.
4. Handle Results:
- If validation succeeds, proceed with further processing of the JSON data.
- If validation fails, handle the errors appropriately, such as:
- Displaying error messages to the user
- Logging errors for debugging
- Terminating the application if necessary
Console App Considerations:
- Input/Output: Use appropriate console input/output methods to read the schema and data files, and display validation results.
- Error Handling: Implement robust error handling to catch exceptions and provide meaningful feedback to the user.
- Library Integration: Ensure the chosen validation library is compatible with your console app's development environment and dependencies.
Example (Python):
```python
import json
from jsonschema import validate
# Load schema and data
with open("schema.json") as f:
schema = json.load(f)
with open("data.json") as f:
instance = json.load(f)
# Validate
try:
validate(instance, schema)
print("JSON data is valid!")
except jsonschema.ValidationError as e:
print("JSON data is invalid:", e)
```
Key Points:
- Reusability: JSON schema validation scripts are often reusable across different environments.
- Library Choice: Select a library that aligns with your programming language and requirements.
- Error Handling: Implement robust error handling for user-friendly validation feedback.
Nice Video Raghav. But U have a question. Why do we need to keep schema JSON in Target/Class path? T
Hi Praveen, so it can directly refer from there
Hi Raghav, for POST Request I need to pass some 30 line of Request body. How to handle that .
Bhuvaneswari
There are two ways to handle a 30-line request body in a POST request using Rest Assured:
1. *Use a string:* You can simply pass the request body as a string to the `body()` method. For example:
```java
String requestBody = """
{
"name": "John Doe",
"age": 30,
"occupation": "Software Engineer",
...
}
""";
given()
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.post("/users");
```
2. *Use a file:* If the request body is very large or complex, you can store it in a file and then pass the file to the `body()` method. For example:
```java
File requestBodyFile = new File("request_body.json");
given()
.contentType(ContentType.JSON)
.body(requestBodyFile)
.when()
.post("/users");
```
Which method you choose depends on your specific needs. If the request body is relatively small and simple, then you can simply pass it as a string. If the request body is very large or complex, then you should store it in a file and then pass the file to the `body()` method.
Here are some additional tips for handling a 30-line request body in a POST request using Rest Assured:
* Use a JSON parser to parse the request body into a JSON object. This can be useful for validating the request body or for extracting data from the request body.
* Use a string builder to build the request body. This can be useful for creating a complex request body from multiple parts.
* Use a file reader to read the request body from a file. This can be useful for handling very large request bodies.
I hope this helps
Hi Raghav !!! can we get a tutorial on API Testing with the BDD framework .....means using feature files, step definition files, and runner files, and all.............the kind-hearted is for your reply
I will plan Hari
Hello Raghav, I have a query.. in my automation, while testing we use device, and test report on web page. Is there any way in selenium we can listen to my web app server where device sending request/ respond
Hi Reshma, I believe Selenium may not be the best fit, it is primarily for browser automation
hello raghav can you please provide the link of initial parts of this video series.. please...
Hi Faraz, sure, can check here - automationstepbystep.com/
@@RaghavPal thankyousomuch
Hello Raghav I have a question ...how to learn protractor with javascript from the basic actually I don't know anything about coding and I already follow ur series but I am facing a lot issue.I mean according to my organization requirement I am not able to design script according to test case because I don't know anything about coding but my manager give the same task for everyone and I am facing so many problems plz help me. Like how to write scripts 😭
@Anjali : For your information Protractor is going to deprecate in near future. My request is to please stop learning it if u plan to learn. Instead go with cypress
@@tulasiramsunkara I know but for task I have to learn.
Hi Anjali, you can first do a basic programming tutorial and then do the framework
@@RaghavPal thanks for your response one more thing can you please share the link basic programming tutorial which I have to follow.
Hi Anjali, you can check here automationstepbystep.com/
Hi Raghav - Sir I am getting the "Schema to use cannot be null" exception because the json file is getting auto-cleaned up / deleted from the target folder. How to fix this?
Rohit
There are a few possible reasons why the JSON file might be getting deleted:
* Eclipse's automatic build process might be cleaning up the target folder.
* A plugin or feature in Eclipse might be configured to delete files in the target folder.
* Your project's configuration or build script might be deleting the file.
Step 1: Check Eclipse's build settings
Check your Eclipse project's build settings to see if there's a configuration that's causing the file to be deleted. You can do this by:
* Going to Project > Properties > Builders
* Checking the "Clean" tab to see if there's a pattern that matches your JSON file
* Checking the "Output Folder" tab to see if the target folder is being cleaned
Step 2: Check for plugins or features
Check if you have any plugins or features installed in Eclipse that might be causing the file deletion. You can do this by:
* Going to Help > Eclipse Marketplace
* Checking if you have any plugins installed that might be related to file cleanup or build processes
Step 3: Check your project's configuration and build script
Check your project's configuration files (e.g., pom.xml if you're using Maven) and build scripts to see if there's a configuration that's causing the file to be deleted.
Step 4: Fix the issue
Based on your findings, you can try one of the following solutions:
* If Eclipse's build settings are causing the file deletion, update the settings to exclude the JSON file from the clean process.
* If a plugin or feature is causing the file deletion, disable or uninstall the plugin.
* If your project's configuration or build script is causing the file deletion, update the configuration to preserve the JSON file.
Additional Tips:
* Make sure the JSON file is in the correct location and is being copied to the target folder correctly.
* Check if you're using a relative or absolute path to reference the JSON file in your Rest Assured tests.
* Consider using a more robust way to manage your JSON schema files, such as storing them in a separate folder or using a schema management tool.
-
Hi Raghav , i have a question but not related to this video , am doing selenium with java ui automation using testNg framework , now i gave demo to my manager by showing code in eclipse IDE and how it runs , but he wants the complete project as a single file and he needs to run from his machine . how can we achieve it ? as a layman he don't want to install eclipse or other required stuff , he needs to run with single command or click , like postman collection can be run thru newman run "url". so could you pls let me know how to achieve it. if we convert my project to jar can we run ?
Hi Moses, best will be to upload the project on a cloud repo and have commands to clone and run from any system
Hi Raghav. I am facing some issues. I have added schema.json file into Target>>classes Folder but don't know why it is automatically gets removed from the target folder. Please help me.
Hi Bhuvanesh, this must help stackoverflow.com/questions/44797895/stop-eclipse-from-deleting-folders-inside-target
@@RaghavPal This helped raghav. Thanks much👍
Hi Raghav I am Facing some problem with validation can you help me?
Pls tell me the details Amol
Hi Sir, I tried this but getting an error for "assureThat()". The method assertThat() is undefined for the type Response. please give the solution
Hi Prasad
The `assureThat()` method is not a method of the `Response` class in Playwright. It is a method of the `expect` function, which is used to make assertions in Playwright tests.
To assert something about a `Response` object, you can use the `expect` function with the `toEqual()` matcher. For example, the following code asserts that the status code of the `Response` object is 200:
```
const response = await page.request('example.com');
expect(response).toEqual({
status: 200,
});
```
The `assertThat()` method is a method of the `Assert` class in JUnit. If you are using JUnit to write your Playwright tests, you can use the `assertThat()` method to make assertions about `Response` objects. For example, the following code asserts that the status code of the `Response` object is 200:
```
import org.junit.Assert;
public class MyTest {
@Test
public void testResponse() {
const response = await page.request('example.com');
Assert.assertThat(response, Matchers.hasProperty("status", 200));
}
}
```
I hope this helps
@@RaghavPal Hi Sir. Thanks for the detailed information. actually its my mistake I used "assertThat()" after "get()". That's why I was getting this error. But now it is showing another error "Schema to use cannot be null"
Sir can we do contract testing using Rest-assured?
Hi Ali
No, Rest-assured is a Java-based library for testing RESTful APIs, but it is not designed specifically for contract testing. Contract testing involves verifying that two communicating systems, such as a client and a server, adhere to an agreed-upon interface or contract. It ensures that changes made to one system do not break the other system's functionality.
Rest-assured can be used to write tests that validate the functionality of RESTful APIs, which can be part of the overall contract testing process.
@@RaghavPal Sir do we have any open source tool for contract testing other than PACT?
Yes, there are several open source tools available for contract testing, in addition to PACT. Here are a few options you can consider:
Spring Cloud Contract: Spring Cloud Contract is an open source framework that allows you to write consumer-driven contract tests in Spring-based applications. It supports several messaging protocols and can generate stubs and tests for both the consumer and provider sides of the contract. Spring Cloud Contract also integrates with popular testing frameworks like JUnit and TestNG.
Hoverfly: Hoverfly is an open source API simulation and testing tool that can be used for contract testing. It allows you to simulate API responses and generate contract tests automatically. It supports several languages and protocols and can be integrated with popular testing frameworks like JUnit and TestNG.
Pactum: Pactum is a lightweight, open source contract testing library that can be used to test RESTful APIs. It supports both JSON and XML request and response payloads and can generate stubs and tests automatically. Pactum also integrates with popular testing frameworks like Mocha and Jest.
Karate DSL: Karate DSL is an open source testing framework that can be used for contract testing. It supports both HTTP and HTTPS protocols and allows you to write tests in a simplified, English-like syntax. Karate DSL also provides built-in support for data-driven testing and can be integrated with popular CI/CD tools like Jenkins.
These are just a few examples of open source contract testing tools available. The best tool for your needs depends on your specific requirements and preferences.
Before modifying the email field from string to integer and running the program, I got an error - Schema to use cannot be null. I resolved the issue by placing the schema.json file to src/test/folder
Hi Aakash, thanks for adding this
Hi Aakash, thanks for adding this
same error could yo please help me
@@RaghavPal Hi Raghav. I am facing the same issue.. I have added schema.json file into Target>>classes Folder but don't know why it is automatically gets removed from the target folder. I've also tried to put it into src/test folder but the same issue is occurred. Please help me.
@@automationqa3304 hi u solve this problem.. M also facing same problem.. Can u help me?
Why we need to validate this? What is the purpose?
Hi Daniel, sometimes it is required and also a good practice to check your json is as per the schema, that defines the structure and format of the json, This will help you further - ua-cam.com/play/PLhW3qG5bs-L992N-g4IgeNirZ1KY5WrkO.html
Hi Raghav, while running my code it getting the error "Schema to use cannot be null"
Hi Nikhil, check this discussion stackoverflow.com/questions/54093212/restassured-java-lang-illegalargumentexception-schema-to-use-cannot-be-null
Could you tell me other api methods
Sure can check the playlist here automationstepbystep.com/
Sir how to use soft assertion here
I will try to add some details or sessions on this
Thank you
i have got an error for equalto and hasItems
where i am getting wrong can u please tell me ?
will need to get more details and logs
Hi Sir till 9th video,we do not discuss json schema,do I need to learn from seperate video,please guide me
Can check this Seenu - ua-cam.com/video/kK-_gL7Vsc0/v-deo.html
only get method is working,post method response content key created at : time how to deal with it..it changes dynamically...
Hi Ravi, you can use regular expressions or wild characters for dynamic content
👍👌
Thanks for watching
i am getting an error its showing schema can not be null
Jaimin
While I don't have access to the specific query responses and ratings you mentioned, I can provide general guidance and potential solutions based on common causes of this error:
Understanding the Error:
- This error usually indicates that Rest Assured is unable to locate or access the JSON schema file you're trying to use for validation.
- Double-check that you've provided the correct file path or schema object to the relevant validation methods.
Troubleshooting Steps:
1. Verify Schema Path:
- Ensure the path you're specifying in your code points to the exact location of the schema file relative to your project directory.
- If it's an external URL, confirm that the URL is reachable and doesn't require authentication.
- Consider using absolute paths or classpath-relative paths for clarity.
2. Inspect Schema Content:
- Make sure the schema file is valid JSON and doesn't contain syntax errors. Use JSON validators or linters to check for issues.
- Verify that the schema structure aligns with the expected response from the API endpoint you're testing.
3. Check Schema Object Construction:
- If you're building the schema dynamically, ensure you're using the correct methods and providing valid data according to Rest Assured's schema API.
- Double-check for typos or incorrect values in your schema construction code.
4. Handle Null Schemas:
- If the schema might be null in certain scenarios, implement logic to handle that gracefully. You could conditionally apply validation or provide a default behavior.
5. Consider Other Possibilities:
- If the above steps don't resolve the issue, provide more context about your test code, schema location, and the specific method you're using for validation.
- Check for compatibility issues between your Rest Assured version and any external libraries you're using for schema handling.
Code Example (Basic Case):
```java
import static io.restassured.module.jsonschema.JsonSchemaValidator.*;
// Assuming you have a valid JSON schema file named "schema.json" in your project's resources directory
String schemaPath = "classpath:schema.json";
given()
./* other request setup */
.when()
.get(/* your API endpoint */)
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath(schemaPath));
```
I hope this helps..
Hi Raghav getting this error .
cannot see the error message
Control+ shift +O
yes, to manage all imports can do this
Hi sir,
I'm facing one challenge.
The challenge is " Copy the session ID value from cookies field in the the first user and paste the same session ID value in the second user and now send the request in postman expected response "401 unauthorized" how to automate this question on rest assured" ?
Hi Mahesh
Here is the code to automate the challenge on Rest Assured:
```
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
public class RestAssuredChallengeTest {
@Test
public void testUnauthorizedAccess() {
// Get the session ID from the first user
String sessionId = getSessionIdFromFirstUser();
// Try to access the resource with the session ID from the first user
given()
.cookie("sessionId", sessionId)
.when()
.get("/resource")
.then()
.statusCode(401);
}
private String getSessionIdFromFirstUser() {
// Get the response from the first user
Response response = given()
.when()
.get("/resource");
// Get the session ID from the cookies
return response.cookies().get("sessionId");
}
}
```
This code will first get the session ID from the first user. Then, it will try to access the resource with the session ID from the first user. Finally, it will check the status code of the response, which should be 401.
To run this code, you will need to have Rest Assured installed. You can install Rest Assured using the following command:
```
mvn install org.rest-assured:rest-assured:latest
```
Once you have installed Rest Assured, you can run the code by running the following command:
```
mvn test
```
This will run the test and print the results to the console. If the test passes, you will see the following output:
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.036 s - in RestAssuredChallengeTest
If the test fails, you will see the following output:
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.036 s - in RestAssuredChallengeTest
The error message will tell you why the test failed.
@raghav when trying to import getting error. import static io.restassured.module.jsv.JSONSchemaValidator.matchesJSONSchemaInClasspath; what could be the reason? java: package io.restassured.module.jsv does not exist
Andy
The error you're encountering suggests that the io.restassured.module.jsv package is not found. This package is part of the Rest Assured library, specifically for JSON schema validation
One possible reason for this issue is that you might be missing the necessary dependency in your project's pom.xml file. You need to include the following dependency to use JSON schema validation:
com.jayway.restassured
json-schema-validator
2.1.0
Make sure to add this dependency to your project's pom.xml file and try importing the JSONSchemaValidator class again
Another possible reason could be that you're using an older version of Rest Assured that doesn't have the io.restassured.module.jsv package. You can try updating your Rest Assured version to the latest one
-
java.lang.IllegalArgumentException: Schema to use cannot be null
getting this error
Afwan
The error message you're encountering-"java.lang.IllegalArgumentException: Schema to use cannot be null"-indicates that the schema you're trying to use for JSON validation is null. Let's troubleshoot this issue:
1. Check Your Schema File:
- Ensure that the JSON schema file you're using for validation exists and is accessible.
- Verify that the file path is correct and that the schema content is valid.
2. Use Correct Schema Path:
- When using `matchesJsonSchemaInClasspath`, make sure the schema file is in the correct location relative to your classpath.
- The schema file should be in the `src/test/resources` directory (or a subdirectory within it).
- Example:
```java
.body(matchesJsonSchemaInClasspath("schemas/my-schema.json"))
```
3. Check for Null Values:
- If you're dynamically loading the schema content, ensure that it's not null.
- Double-check any logic that sets the schema content.
4. Verify Dependencies:
- Make sure you have the necessary dependencies for JSON schema validation.
- Ensure that you're using the correct version of the library (e.g., `io.rest-assured:json-schema-validator`).
5. Test with a Simple Schema:
- Temporarily use a simple schema (even an empty one) to see if the issue persists.
- If it works with a basic schema, gradually add complexity to your schema.
6. Inspect Your Test Code:
- Review your test code to ensure that you're correctly invoking the schema validation.
- Check if there are any null assignments or missing steps.
7. Update Dependencies:
- If you're using an older version of Rest Assured or its dependencies, consider updating to the latest version.
Remember to adapt these steps based on your specific project structure and requirements
.
java.lang.IllegalArgumentException: Schema to use cannot be null I'm getting this error ,can anyone please give me the answer to correct it
Joseph
Let's break down the problem step by step.
Problem: The error indicates that the schema to use is null, which is not allowed.
Possible Causes:
1. Missing or invalid schema configuration: Rest Assured uses a schema to validate the response. If the schema is not provided or is invalid, it will throw this error.
2. Incorrect usage of `given()` or `expect()` methods: The `given()` and `expect()` methods in Rest Assured are used to specify the request and response specifications, respectively. If these methods are not used correctly, it can lead to this error.
Step-by-Step Solution:
1. Check your Rest Assured configuration: Make sure you have properly configured Rest Assured to use a schema. You can do this by specifying the schema using the `schema` method or by providing a JSON schema file.
Example:
```java
RestAssured.config = RestAssured.config().schemaConfig(new SchemaConfig().with().mimeTypes("application/json", "json"));
```
2. Verify your request specification: Check that you are using the `given()` method correctly to specify the request details.
Example:
```java
given()
.header("Content-Type", "application/json")
.body(requestBody)
.when()
.post("/api endpoint");
```
3. Verify your response specification: Check that you are using the `expect()` method correctly to specify the response details.
Example:
```java
expect()
.statusCode(200)
.body("key", equalTo("value"));
```
4. Check for null values: Ensure that you are not passing null values to the `given()` or `expect()` methods.
Example:
```java
// Avoid this:
given().body(null);
// Instead, use an empty string or a valid request body:
given().body("");
```
5. Review your JSON schema file (if using): If you are using a JSON schema file, ensure that it is valid and correctly configured.
Example:
```java
// schema.json file:
{
"$schema": "json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"key": {"type": "string"}
}
}
```
By following these steps, you should be able to identify and fix the issue
-
Hi raghav i have send you request on skype please accept it ?
Hi Vipin, I rarely use skype, You can message me here