How to use cy.prompt in Cypress; this blog introduces cy.prompt, an experimental tool from Cypress designed to simplify web automation by allowing users to write tests using natural language descriptions rather than complex CSS selectors. By leveraging artificial intelligence, the platform enables self-healing capabilities; as a result, tests automatically adapt to UI changes like renamed buttons without failing the entire build. This innovation significantly accelerates test authoring and maintenance, empowering team members without deep coding knowledge to participate in the quality assurance process. Furthermore, the system avoids the limitations of typical AI “black boxes” by providing transparent debugging logs and the option to export AI-generated steps into standard code for long-term stability and peer review.Ultimately, this technology promotes broader team participation by allowing non-technical members to contribute to the testing process without deep knowledge of JavaScript.
In 2025, the release of cy.prompt() fundamentally shifted how teams approach end-to-end testing by introducing a native, AI-powered way to write tests in plain English. This experimental feature, introduced in Cypress 15.4.0, allows you to describe user journeys in natural language, which Cypress then translates into executable commands.
Why use cy.prompt()?
Reduced Maintenance: If a UI change (like a renamed ID) breaks a test, cy.prompt() can automatically regenerate selectors through its self-healing capability.
Faster Test Creation: As a result, you can go from a business requirement to a running test in seconds without writing manual JavaScript or hunting for selectors.
Democratized Testing: Consequently, product managers and non-technical stakeholders are empowered to contribute to automation through Gherkin-style steps in the test suite.
Generate and Eject (For Stable Apps):To start, use cy.prompt() to scaffold your test. Once generated, click the “Code” button in the Command Log and save the static code to your spec file; this approach is ideal for CI/CD pipelines that require strictly deterministic, frozen code.
Continuous Self-Healing (For Fast-Paced Development): Keep the cy.prompt() commands in your repository. Cypress will use intelligent caching to run at near-native speeds on subsequent runs, only re-calling the AI if the UI changes significantly.
Why it’s “Smart”:
Self-Healing: If a developer changes a class to a test-id, cy.prompt() won’t fail; it re-evaluates the page to find the most logical element.
Speed: It uses Intelligent Caching. The AI is only invoked on the first run; subsequent runs use the cached selector paths, maintaining the lightning-fast speed Cypress is known for.
How to Get Started? How to use cy.prompt in Cypress?
1. Prerequisites and Setup
How to use cy.prompt in Cypress? for AI-driven end-to-end testing with self-healing selectors and faster test creation. Before you can run a program with cy.prompt(), you must configure your environment:
Version Requirement: Ensure you are using Cypress 15.4.0 or newer.
Enable the Feature: Open your cypress.config.js (or .ts) file and set the experimentalPromptCommand flag to true within the e2e configuration.
Authenticate with Cypress Cloud: cy.prompt() requires a connection to Cypress Cloud to access the AI models.
Local development: Log in to Cypress Cloud directly within the cypress app.
CI/CD: Use your record key with the –record –key flag.
2. Writing Your First Test
The command accepts an array of strings representing your test steps.
describe('Prompt command test', () => {
it('runs prompt sequence', () => {
cy.prompt([
"Visit https://aicotravel.co",
"Type 'Paris' in the destination field",
"Click on the first search result",
"Select 4 days from the duration dropdown",
"Press the **Create Itinerary** button"
])
})
})
The “smart” way to use cy.prompt() is to combine it with standard commands for a hybrid, high-reliability approach.
describe('User Checkout Flow', () => {
it('should complete a purchase using AI prompts', () => {
cy.visit('/store');
// Simple natural language commands
cy.prompt('Search for "Wireless Headphones" and click the first result');
// Using placeholders for sensitive data to ensure privacy
cy.prompt('Log in with {{email}} and {{password}}', {
placeholders: {
email: 'testuser@example.com',
password: 'SuperSecretPassword123'
}
});
// Verify UI state without complex assertions
cy.prompt('Ensure the "Add to Cart" button is visible and green');
cy.get('.cart-btn').click();
});
});
3. The “Smart” Workflow: Prompt-to-Code
Most professional way to use cy.prompt() is as a code generator.
Drafting: Write your test using cy.prompt().
Execution: Run the test in the Cypress Open mode.
Conversion: Once the AI successfully finds the elements, use the “Convert to Code” button in the Command Log.
Save to File: Copy the generated code and replace your cy.prompt() call with it. Consequently, this turns the AI-generated test into a stable, version-controlled test that runs without AI dependency.
Commit: However cypress will generate the standard .get().click() code based on the AI’s findings. You can then commit this hard-coded version to your repository to avoid unnecessary AI calls in your CI/CD pipeline.
4. Best Practices:
Imperative Verbs: Start prompts with “Click,” “Type,” “Select,” or “Verify.”
Contextual Accuracy: If a page has two “Submit” buttons, be specific: cy.prompt(‘Click the “Submit” button inside the Newsletter section’).
Security First: However, never pass raw passwords into the prompt string. Therefore, always use the placeholders configuration to keep sensitive strings out of the AI logs.
Hybrid Strategy: Ultimately, use cy.prompt() where flexibility is needed for complex UI interactions, and fall back to standard cy.get() for stable elements like navigation links.
The introduction of cy.prompt() marks the end of “selector hell.” By treating AI as a pair-programmer that handles the tedious task of DOM traversing, we can write tests that are more readable, easier to maintain, and significantly more resilient to UI changes.
Jyotsna is a Jr SDET which have expertise in manual and automation testing for web and mobile both. She has worked on Python, Selenium, Mysql, BDD, Git, HTML & CSS. She loves to explore new technologies and products which put impact on future technologies.
Pytest Vs Unittest: Testing forms the backbone of reliable software development, and in Python, two major frameworks stand out to get the job done: Unittest and Pytest. While both aim to ensure code correctness, maintainability, and robustness, they take very different approaches. Moreover, Python includes Unittest as a built-in framework, offering a familiar class-based testing style without requiring extra dependencies. Pytest, on the other hand, is a modern, feature-rich alternative that emphasizes simplicity, readability, and powerful capabilities like parametrization and fixtures.
In this blog, we’ll break down the key differences, advantages, and practical examples of both frameworks—helping you decide when to stick with the reliability of Unittest and when to embrace the flexibility of Pytest for your projects. Let’s see the Pytest vs Unittest: Which Python Testing Framework to Choose?
Step 1: Understanding the Fundamentals of Pytest Vs Unittest
What is Unittest?
Unittest comes bundled with Python as part of its standard library. Therefore, it ensures immediate availability and compatibility across different environments without requiring extra dependencies. Moreover, the seamless integration across environments makes Unittest convenient to use without the need for additional packages. To begin with, unit testing represents the first level of software testing, where testers examine the smallest parts of a program to ensure each unit functions as designed.
Example:
import unittest
class SimpleTest(unittest.TestCase):
def test_example(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
For example, this is the basic test code using the Unittest framework, which contains a single test. This test() method will fail if True is ever false.
Output:
OOps concepts supported by unittest framework:
Text Fixture: A test fixture provides a baseline for running the tests. It basically provides the prerequisites needed for executing one or more tests and any clean up or temporary database generation running the process with all these functionality handled by text fixture.
Test Case: A set of cases defines the conditions that determine whether a system under test works correctly. It is a collection of unit tests
Test Suite: In addition, a test suite is a collection of test cases used to verify that a software program exhibits a specified set of behaviors by executing the aggregated tests together.
Test Runner: Similarly, a test runner is a component that sets up the execution of tests and provides the outcomes to the user. Furthermore, the runner may use a graphical interface, a text-based interface, or return a special value to indicate the results of executing tests.
Sample example of Unit test fixture:
import unittest
class SimpleTest(unittest.TestCase):
def setUp(self):
# This is the fixture. Runs before every test.
self.data = [1, 2, 3]
def tearDown(self):
# Clean up here (optional). Runs after every test.
self.data = None
def test_sum(self):
self.assertEqual(sum(self.data), 6)
def test_max(self):
self.assertEqual(max(self.data), 3)
if __name__ == '__main__':
unittest.main()
What is Pytest?
Overall, Pytest is a robust testing framework for Python that makes it easier to write simple and scalable test cases. In fact, Pytest’s simple syntax lets developers get started quickly with minimal boilerplate code. In addition, it supports fixtures, parametrization, and numerous plugins, making it a versatile and powerful tool for writing and organizing test cases.
Example:
import pytest
@pytest.mark.smoke
def test_function_one():
print('inside test function test_function_one')
num = 10
assert num !=12
Output:
Pytest Text Fixture:
Here’s a list of some of the most popular pytest fixtures you’ll often see used:
tmp_path / tmpdir: Provides a temporary directory unique to the test run.
monkeypatch: Allows you to modify or “patch” functions or environment variables for the duration of a test.
capfd / capsys: Captures output to file descriptors/stdout/stderr.
request: Gives access to the test context for parametrization, data, etc.
db (often custom): Sets up and tears down a database connection.
client: Creates a test client for web applications.
autouse fixtures: Moreover, Pytest automatically applies fixtures without requiring you to declare them in a test function.
parametrized fixtures: Moreover, you can deliver different values to tests using the same fixture code, enabling you to run tests against multiple inputs.
Step 3: Writing tests(Automation using Pytest Vs Unittest)
Writing tests using unittest
To begin with, create a project and add a Python package named business_logic. Inside this package, create two Python files: calculator.py and login.py.
Login.py:
USER = "Admin"
PASS = "Admin123"
def authenticate_user(username,password):
if username:
if password:
if USER==USER and PASS==password:
return 'Login Successful'
else:
return 'Invalid Credentials'
else:
return 'Password Cannot Be Empty...'
else:
return 'Username cannot be Empty...'
For example, the above simple code authenticates the user with a valid username and password. If the entered credentials match the predefined ‘Admin’ and ‘Pass’, the user successfully logs in to the application. If it’s not matching the criteria it will give a warning message popup.
Calculator.py:
def addition(n1,n2):
if type(n1) in [int,float,complex] and type(n2) in [int,float,complex]:
if n1<=0 or n2<=0:
return 'Number shud be greater than zero'
return n1+n2
else:
return 'Invalid Input'
In above code a simple calculator method is used for calculator additional functionality where n1 and n2 are could be [int,float,complex] if n1 or n2 are <=0 it will return warning popup message ‘Number shud be greater than zero’ and when n1 or n2>0 it will return addition of n1 and n2 else it will give warning popup message as ‘Invalid Input’.
Test_login_scenario.py:
import unittest
from business_logic.login import authenticate_user
class TestLogin(unittest.TestCase):
def test_valid_username_and_password(self):
if (authenticate_user('user0','pass0'))==True:
return True
print('inside test_valid_username_and_password')
def test_invalid_username_and_password(self):
print('Inside test_invalid_username_and_password')
self.assertEqual(10,20)
For instance, the above unit test verifies the login functionality for both positive and negative scenarios using Python’s built-in library.
Writing tests using pytest
from business_logic.calculator import addition
import pytest
import threading
@pytest.mark.parametrize("n1,n2,expected_result",[
(10,20,30),
(10,"A","Invalid Input"),
(0, "A", "Invalid Input"),
(0,10, "Number shud be greater than zero"),
(0,0,"Number shud be greater than zero"),
(10,-2,"Number shud be greater than zero"),
(2,4,6)
])
def test_calculator(n1,n2,expected_result):
print(n1,n2,expected_result)
result = addition(n1,n2)
assert result == expected_result
Similarly, in the above code, we have used Pytest parameterization to test the calculator’s addition functionality with the Pytest library.
Step 4: Run code through Command line
Unittest important commands:
Python -m unittest —> This is use to search entire test cases Example – python -m unittest tests.module.testclass
Python -m unittest -v test_module —> Here -v is used for more details
Python -m unittest -h —> -h is used for all command line help options
-f —> -f is used to stop the test run on the first error or failure
-k —> It is use to run the test methods and classes that matches the pattern or substring
Pytest important commands:
Pytest test_module() —> This is used to run tests in module
Pytest tests/ —> This is used to run tests in directory
f – failed
E – error
s – skipped
x – xfailed
X – xpassed
p – passed
P – passed with output
Step 5: Advantages of using Pytest and Unittest
Advanced Features of Unittest
Test discovery: Automatically finds and runs tests.
Test suites: Group multiple tests together.
Mocking capabilities: Use unittest.mock for mocking objects.
Advanced Features of Pytest
Parametrization: Easily run a test with multiple sets of parameters.
Plugins: A rich ecosystem of plugins to extend functionality.
Step 6: Key comparison between unittest and pytest
Aspect
Unittest
Pytest
Included with Python
Yes (Standard Libraries)
No (third-party package, install needed)
Syntax
More verbose, class-based
Simple, concise, function-based
Test Discovery
Requires strict naming and class structure
Automatic, flexible
Fixtures
Limited to setUp/tearDown methods
Powerful, modular fixtures with scopes
Parameterization
No built-in support (needs custom handling)
Built-in @pytest.mark.parametrize
Assertions
Assertion methods (e.g., assertEqual)
Plain assert with detailed introspection
Plugins
Few, limited support
Large rich ecosystem
Test Execution Speed
Sequential by default
Supports parallel execution
Mocking
Uses unittest.mock
Compatible with unittest.mock and plugins
Learning Curve
Easier for beginners
Moderate due to more features
Community
Standard library with stable adoption
Large and active community
Conclusion
Both Unittest and Pytest help you write reliable, maintainable tests—but they serve different needs. On the other hand, Unittest is lightweight, built-in, and well-suited for straightforward or legacy projects. In contrast, Pytest is modern, concise, and equipped with powerful features like fixtures, plugins, and parametrization—making it ideal for larger or more complex testing needs.
If you want simplicity with no extra setup, go with Unittest. If you want flexibility, readability, and speed, choose Pytest.
Jyotsna is a Jr SDET which have expertise in manual and automation testing for web and mobile both. She has worked on Python, Selenium, Mysql, BDD, Git, HTML & CSS. She loves to explore new technologies and products which put impact on future technologies.
A domain name is an online address that offers a user-friendly way to access a website. In the context of Verified domains Python, this refers to verifying that a domain is legitimate and active using Python programming techniques. In the internet world IP address is a unique string of numbers and other characters used to access websites from any device or location. However, the IP address is hard to remember and type correctly, so the domain name represents it with a word-based format that is much easier for users to handle. When a user types a domain name into a browser search bar, it uses the IP address it represents to access the site.
The Domain Name System (DNS) maps human-readable domain names (in URLs or email addresses) to IP addresses. This is the unique identity of any website or company/organization which makes any website unique and verified, It’s still possible for someone to type an IP address into a browser to reach a website, but most people want an internet address to consist of easy-to-remember words, called domain names for example: Google. , Amazon. Etc. and domain names come with different domain extensions for example: Amazon. in, Google.com
A domain also serves several important purposes on the internet. Here are some key reasons why a domain is necessary:
Identification: Domain names are easier to remember than IP addresses, making it simpler to locate resources online.
Branding: A domain name is vital for building a professional online identity, reflecting the nature and purpose of a business.
Credibility: Owning a domain enhances professionalism, showing commitment to a unique online presence.
Email Address: A personalized email linked to a domain looks more professional and builds trust.
Control: Domain ownership gives you control over hosting, email management, and associated content.
SEO: A relevant, keyword-rich domain can improve search engine visibility.
Portability: Owning a domain allows you to change hosting providers while keeping the same web address, ensuring consistency.
Why do we need domain verification?
Verifying a domain name is a key step for businesses and individuals looking to establish credibility, and control over their content, and enhance their presence on digital platforms.
Let’s Understand this using the example:
Verifying your domain helps Facebook to allow rightful parties to edit link previews directly to your content.
This allows you to manage editing permissions over links and contents and prevents misuse of your domain. This includes both organic and paid content.
These verified editing permissions ensure that only trusted employees and partners represent your brand.
Domain Verification Techniques:
Domain verification is a crucial step to make sure your domain is active and not expired. When a domain is verified, users are automatically added to the Universal Directory, so they don’t have to wait for personal approval to log in. This process helps confirm that the domain is legitimate and prevents issues related to fake or misused domains. These are some techniques through which we can verify our domain.
WHOIS Lookup
Requests & Sockets
DNS Verification
Let’s see how we can verify valid domains to find verified domains using Python, you can employ several approaches listed below.
1) WHOIS Lookup:
Use the WHOIS module in Python to perform a WHOIS lookup on a domain. This method provides information about the domain registration, including the registrar’s details and registration date.
Install the whois module using pip install python-whois.
def check_domain(domain):
try:
# Attempt to retrieve information about the given domain using the 'whois' library.
domain_info = whois.whois(domain)
# Check if the domain status is 'ok' (verified).
if domain_info.status == 'ok':
print(f"{domain} is a verified domain.")
else:
print(f"{domain} is not a verified domain.")
# Handle exceptions related to the 'whois' library, specifically the PywhoisError.
except whois.parser.PywhoisError:
print(f"Error checking {domain}.")
# Handle exceptions related to the 'whois' library, specifically the PywhoisError.
except whois.parser.PywhoisError:
print(f"Error checking {domain}.")
2) Request & Socket
Use Python’s request lib and socket to find verified domains For this we need to install these python dependencies requests & socket
Here we are passing hostname as a parameter and socket.gethostbyname(hostname) will give us the IP address for the host socket.create_connection((ip_address, 80)) is used for the socket to bind as a source address before making the connection. When we pass hostname or domain name with the correct extension to this function for example as given in the above function i.e “google.net” it will return True And if the hostname/domain is incorrect it will return false.
To verify a domain in Python, you can use various approaches depending on the type of verification required. Here, is one of the common methods: DNS verification
DNS Verification:
DNS verification involves checking if a specific DNS record exists for the domain. For example, you might check for a TXT record with a specific value.
import dns.resolver
def verify_dns(domain, record_type, expected_value):
try:
answers = dns.resolver.resolve(domain, record_type)
for rdata in answers:
if rdata.to_text() == expected_value:
return True
except dns.resolver.NXDOMAIN:
pass
return False
# dns.resolver.resolve attempts to resolve the specified DNS record type for the given domain
domain = "google.com"
record_type = "TXT"
expected_value = "v=spf1 include:_spf.google.com ~all"
This is a Valid example of the above function where the domain is “google.com”, the function returns True when the record type is “TXT” and the expected value matches Google’s SPF TXT record. If no match is found or if the domain does not exist (it will give an NXDOMAIN exception), it returns False.
A domain name is a crucial component of your online identity, providing a way for people to find and remember your website or online services. Whether for personal use, business, or any other online endeavor, having a domain name is an essential part of establishing a presence on the internet.
Each approach serves a distinct purpose in verifying a domain’s legitimacy. Choose the verification method based on your specific use case and requirements. Verified domains Python methods like DNS verification are often used for domain ownership verification, while WHOIS Lookup provides essential registration details.
Click here to read more blogs like this and learn new tricks and techniques of software testing.
Jyotsna is a Jr SDET which have expertise in manual and automation testing for web and mobile both. She has worked on Python, Selenium, Mysql, BDD, Git, HTML & CSS. She loves to explore new technologies and products which put impact on future technologies.
Have you ever wondered how online shopping sites such as Amazon, Flipkart, and Meesho suggest or recommend us products depending on our search or browsing history, how they do? This is because their server indexes all the information in their records so they can return the most relevant search-based results. Web crawlers use to handle this process.
Data is becoming the key to growth for any business over the past decade most successful organizations used data-driven decision-making.
with 5 billion users creating billions of data points per second. They get data primarily for price and brand monitoring, price comparison, and big data analysis that serve their decision-making process and business strategy
Web scraping/ crawling is used to find meaningful insights (Data) that will help in making decisions for business growth. Let’s see how we can achieve this.
Web scraping is used to gather a large amount of data from Websites. Doing such a thing manually is very difficult to manage because data available on the web is in an unstructured manner with the help of web scraping we can avoid this. Scraping stores data in a structured manner.
Example – Python web scraping/crawling for Flipkart
Prerequisites – We need the following lib to achieve the scraping of Flipkart, so to install these packages on your system, simply open cmd and run the following commands.
1. Pip install python 3+
2. Pip install selenium
3. Pip install requests
4. Pip install lxml
Once we install all required lib then we are good to go. Now we need to add request headers to scrap the information from the web. To find request headers on the web page follow the steps given below.
Step1:
Open the URL of the webpage you want to scrap/crawl and search for the product name in the search bar you want the information about, products list is displayed on the page, and then click on any product and right-click on the page and click on “inspect”.
Step2:
Now the Html format page is open then select the “Network” option, under this click on the first checkbox it will show all requests and response headers. Just copy the request headers that we need for scraping here.
Step 3:-
Create a python file (file name with .py extension) and import all required libraries which we are going to use.
Here create a file with name >python_scrapy_demo.py
‘sec-ch-ua’: ‘” Not A;Brand”;v=”99″, “Chromium”;v=”99″, “Google Chrome”;v=”99″‘,
‘sec-ch-ua-mobile’: ‘?0’,
‘sec-ch-ua-platform’: “Windows”,
‘Sec-Fetch-Dest’: ‘document’,
‘Sec-Fetch-Mode’: ‘navigate’,
‘Sec-Fetch-Site’: ‘same-origin’,
‘Sec-Fetch-User’: ‘?1’,
‘Upgrade-Insecure-Requests’: ‘1’,
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36’ }
#write method to save html page data in the file
def save_html_page(page_data):
with open(‘flipkart_page.html’,’w+’,encoding=’utf-8′) as fl:
fl.write(page_data)
#write method to save the data in the csv file
def data_save_csv(dt):
headings={‘product_name’,’product_price’}
with open(‘flipkartdata.csv’,’a+’,encoding=’utf-8′) as file:
writer=DictWriter(file,fieldnames=headings)
writer.writeheader()
writer.writerow(dt)
file.close()
In the above code, we are saving html page and writing data into a file, and then we save that data into csv file. Here we write a method for saving html page we use the file open() method to open the file and we use “w+”,encoding=’utf-8” to write data into Unicode transformation. For extracting data (i.e here we extract product_name and product_price) follow the methods given below. We can extract the different types of data by using this code here just need to add xpath of what type of product description we need to extract and it will return the data.
We live in a world where technology continues to develop, particularly in the computer industry. The current market scenario and client demands change every second. Hence to satisfy customer needs and business growth simultaneously we need to make changes in business and it can be achieved using web scraping/crawling.
Jyotsna is a Jr SDET which have expertise in manual and automation testing for web and mobile both. She has worked on Python, Selenium, Mysql, BDD, Git, HTML & CSS. She loves to explore new technologies and products which put impact on future technologies.