Selenium Articles / Blogs / Perficient https://blogs.perficient.com/tag/selenium/ Expert Digital Insights Tue, 31 Dec 2024 06:30:11 +0000 en-US hourly 1 https://blogs.perficient.com/files/favicon-194x194-1-150x150.png Selenium Articles / Blogs / Perficient https://blogs.perficient.com/tag/selenium/ 32 32 30508587 A Beginner’s Guide to Running Selenium Tests on BrowserStack using Pytest https://blogs.perficient.com/2024/12/31/a-beginners-guide-to-running-selenium-tests-on-browserstack-using-pytest/ https://blogs.perficient.com/2024/12/31/a-beginners-guide-to-running-selenium-tests-on-browserstack-using-pytest/#respond Tue, 31 Dec 2024 06:14:57 +0000 https://blogs.perficient.com/?p=374406

In today’s world, testing web applications across multiple browsers and devices is essential. One of the best tools for this is BrowserStack, a cloud-based platform that allows you to run Selenium tests on various real browsers and devices. In this blog, we will walk you through the process of integrating BrowserStack with Python Selenium and running tests using Pytest.

What is BrowserStack?

BrowserStack is a cloud-based testing platform that allows you to run automated tests on real browsers and devices, without needing to set up the infrastructure yourself. It supports various browsers like Chrome, Firefox, Safari, Edge, and even mobile devices like iPhones and Android phones.

Browserstack

Why Use BrowserStack with Selenium?

Selenium is a widely used tool for automating browsers, and with BrowserStack, you can run your Selenium tests on a wide range of browsers and operating systems. This ensures your application works seamlessly across different environments without needing to maintain your own testing infrastructure.

In this guide, we will use Pytest—a popular testing framework for Python—to run tests. This combination provides an efficient and flexible way to conduct cross-browser testing.

Prerequisites

Before you begin, ensure you have the following installed:

  1. Python (Version 3 or above)
  2. Selenium: Install it via pip
    pip install selenium
  3. Pytest: Install it via pip
    pip install pytest
  4. BrowserStack Account: Sign up at BrowserStack and get your username and access key.

Step 1: Set Up BrowserStack

Once you have an account on BrowserStack, you can find your username and access key from the BrowserStack dashboard.

You’ll use these credentials to authenticate your Selenium tests on BrowserStack.

Step 2: Configure Selenium to Use BrowserStack

To configure your Selenium WebDriver to run on BrowserStack, you need to specify BrowserStack’s remote URL, your credentials, and the desired capabilities of the browser or device you wish to test on.

Here is how to set it up:

from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

# BrowserStack credentials
username = "your_browserstack_username"
access_key = "your_browserstack_access_key"

# Desired capabilities to run the test
desired_cap = {
    'browser': 'Chrome',
    'browser_version': 'latest',
    'os': 'Windows',
    'os_version': '10',
    'name': 'Python Selenium BrowserStack Test'  # Test name
}

# BrowserStack URL
url = f"https://{username}:{access_key}@hub-cloud.browserstack.com/wd/hub"

# Pytest Fixture to initialize the driver
@pytest.fixture(scope="function")
def driver():
    driver = webdriver.Remote(
        command_executor=url,
        desired_capabilities=desired_cap
    )
    yield driver
    driver.quit()

# Sample Test Case using Pytest
def test_browserstack(driver):
    driver.get("https://www.browserstack.com")
    assert "BrowserStack" in driver.title

    # Example of interaction
    search_box = driver.find_element(By.NAME, "q")
    search_box.send_keys("Selenium Python")
    search_box.send_keys(Keys.RETURN)

    # Assert something to validate test
    assert "Selenium" in driver.page_source

Key Points:

  • username and access_key: These values authenticate your test on BrowserStack.
  • desired_cap: This dictionary defines the configuration for the browser and OS you want to test on.
    • browser: The browser you want to test (Chrome, Firefox, etc.).
    • browser_version: Version of the browser (e.g., ‘latest’ or ’90’).
    • os: Operating system you want to run the tests on (Windows, macOS, Linux).
    • os_version: Version of the OS.
    • name: A custom name for the test.

Step 3: Running the Test with Pytest

To run the tests with Pytest, simply use the following command in your terminal:

pytest test_browserstack.py

This will trigger the test on BrowserStack, and you can view the results directly on the BrowserStack dashboard.

Step 4: Viewing Test Results on BrowserStack

Once your tests complete, you can visit the BrowserStack Dashboard to view detailed logs, screenshots, and videos of the tests. This can help in debugging any issues with your application.

Conclusion

Integrating BrowserStack with Python Selenium and Pytest is a powerful way to ensure your web application works across different browsers and devices. By using the cloud-based BrowserStack platform, you can avoid the hassle of setting up multiple testing environments and focus on writing effective tests. With Pytest’s simple yet effective testing capabilities, you can execute your cross-browser tests smoothly and efficiently.

If you run into any issues during the setup or execution, make sure to check the BrowserStack documentation for troubleshooting and advanced configuration options.

Happy testing!

]]>
https://blogs.perficient.com/2024/12/31/a-beginners-guide-to-running-selenium-tests-on-browserstack-using-pytest/feed/ 0 374406
Debugging Selenium Tests with Pytest: Common Pitfalls and Solutions https://blogs.perficient.com/2024/12/30/debugging-selenium-tests-with-pytest-common-pitfalls-and-solutions/ https://blogs.perficient.com/2024/12/30/debugging-selenium-tests-with-pytest-common-pitfalls-and-solutions/#respond Mon, 30 Dec 2024 06:20:26 +0000 https://blogs.perficient.com/?p=374409

When automating browser tests with Selenium and Pytest, it’s common to run into challenges. Selenium is a powerful tool, but it can be tricky to troubleshoot and debug. Whether you’re encountering timeouts, stale elements, or incorrect results, understanding how to identify and resolve common issues is essential.

Picture9

In this blog, we’ll walk through some common pitfalls when using Selenium with Pytest and share practical solutions to help you debug your tests effectively.

  • Element Not Found / NoSuchElementException:
    One of the most frequent errors when using Selenium is the NoSuchElementException, which occurs when Selenium cannot locate an element on the page. This usually happens if:

      • The element is not present yet (e.g., it loads dynamically).
      • The selector is incorrect or out-of-date.
      • The element is in a different frame or window.

  • Solution:
    To resolve this, you can use Explicit Waits to ensure the element is present before interacting with it. Selenium provides the WebDriverWait method, which waits for a specific condition to be met (e.g., an element to become visible or clickable).

 

  • Example:
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # Wait for the element to be visible
    wait = WebDriverWait(driver, 10)  # Wait for up to 10 seconds
    element = wait.until(EC.visibility_of_element_located((By.ID, "myElement")))
    element.click()
    

    This will wait for the element to appear within 10 seconds before trying to interact with it.

  • StaleElementReferenceException: The StaleElementReferenceException occurs when you try to interact with an element that is no longer part of the DOM. This can happen if the page is reloaded, or the element gets removed and recreated.

  • Solution:
    To solve this issue, simply re-locate the element before interacting with it again. Using an explicit wait before interacting with the element is also a good practice.

 

  • Example:
    # First locate the element 
    element = driver.find_element(By.ID, "myElement") 
    
    # Perform an action 
    element.click() 
    
    # If the page is updated, re-locate the element 
    element = driver.find_element(By.ID, "myElement") 
    element.click()

     

  • Timeouts (Element Not Interactable): Timeout errors often occur when Selenium takes longer than expected to find or interact with an element. For example, trying to click an element before it’s fully loaded, or interacting with an element that’s hidden

  • Solution:
    Using explicit waits as shown in the first example will help here. But you should also ensure that the element is interactable (visible and enabled) before performing any action on it
  • .
  • Example:
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.ID, "submitButton")))
    element.click()
    

    In this case, element_to_be_clickable ensures that the button is not only present but also interactable (i.e., visible and enabled).

 

  • Wrong Browser Version or Compatibility Issues: Sometimes tests may pass on one browser but fail on another. This is especially common with cross-browser testing.
    Solution: Make sure you’re using the correct browser drivers (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox) that are compatible with the version of the browser you are testing. Also, check if the issue is specific to the browser’s rendering engine.If you’re running tests across multiple browsers, using a cloud testing service like BrowserStack or Sauce Labs is a good way to avoid browser setup issues and test on real environments.

 

  • Logging and Capturing Errors Another issue is tracking and logging errors effectively during the test execution. If you don’t capture logs, it can be hard to identify what went wrong in case of test failure.

  • Solution:
    Incorporating logging within your test can help you keep track of actions and errors, making it easier to identify issues.

 

  • Example:
  • import logging
    
    # Set up logging
    logging.basicConfig(level=logging.INFO)
    
    def test_login(driver):
        logging.info("Opening login page")
        driver.get("https://example.com/login")
    
        logging.info("Filling in login credentials")
        driver.find_element(By.ID, "username").send_keys("user")
        driver.find_element(By.ID, "password").send_keys("pass")
    
        logging.info("Submitting the form")
        driver.find_element(By.ID, "submit").click()
    
        logging.info("Verifying login success")
        assert "Welcome" in driver.page_source
    

    You can view the log output to trace the sequence of events in case a failure occurs.

 

  • Pytest Assertion Errors: Another common issue is assertion errors when the expected value does not match the actual value returned by the test.

  • Solution:
    When you’re running tests with Pytest, ensure that your assertions are meaningful and validate what you really care about. Sometimes, comparing strings or numbers directly may lead to errors if the values have different formats.

 

  • Example:
  • def test_title(driver):
        driver.get("https://example.com")
        assert driver.title == "Expected Title", f"Expected 'Expected Title' but got {driver.title}"
    

    This assertion helps ensure that the test fails gracefully, providing helpful error messages to debug.

 

  • Pytest Markers and Test CategorizationWhen you have a large test suite, running all tests every time can slow down development. Using Pytest markers to categorize tests (e.g., @pytest.mark.smoke) can help you run only relevant tests, making debugging easier..

  • Solution:
    Use markers to tag tests for different categories, such as smoke tests, regression tests, etc.

 

  • Example:
    import pytest
    
    @pytest.mark.smoke
    def test_login(driver):
        driver.get("https://example.com/login")
        assert "Login" in driver.title
    
    @pytest.mark.regression
    def test_logout(driver):
        driver.get("https://example.com/logout")
        assert "Logout Successful" in driver.page_source
    

    Then run only smoke tests or regression tests by specifying the marker:
    pytest -m smoke

 

Conclusion

Debugging Selenium tests with Pytest can be tricky, but by understanding common pitfalls and applying simple solutions, you can save time and improve test reliability. Here’s a quick recap of what we covered:

  • Use explicit waits to handle dynamic elements and timeouts.
  • Re-locate elements if you run into StaleElementReferenceException.
  • Ensure elements are interactable before clicking.
  • Use logging to track the flow and errors in your tests.
  • Leverage Pytest markers to run relevant tests and make debugging easier.

By following these best practices, you’ll become more effective at identifying and resolving issues in your Selenium tests. Happy debugging!

 

]]>
https://blogs.perficient.com/2024/12/30/debugging-selenium-tests-with-pytest-common-pitfalls-and-solutions/feed/ 0 374409
Simplifying CI/CD with Pytest and Selenium for Web Automation Testing https://blogs.perficient.com/2024/12/27/simplifying-ci-cd-with-pytest-and-selenium-for-web-automation-testing/ https://blogs.perficient.com/2024/12/27/simplifying-ci-cd-with-pytest-and-selenium-for-web-automation-testing/#respond Fri, 27 Dec 2024 10:38:23 +0000 https://blogs.perficient.com/?p=374401

In today’s fast-paced software development environment, Continuous Integration (CI) and Continuous Deployment (CD) have become essential practices. They help development teams to integrate code changes frequently, automate tests, and release software faster. In this blog, we’ll explore how Pytest and Selenium can simplify the CI/CD pipeline for web automation testing.

What is CI/CD?

Before diving into Pytest and Selenium, let’s first understand CI/CD:

  • Continuous Integration (CI) is the practice of merging all developers’ working copies to a shared repository frequently, ideally several times a day. This ensures that the codebase is always in a deployable state and allows for faster bug detection.
  • Continuous Deployment (CD) refers to the automatic release of code changes to production once they pass all tests and checks. This reduces manual intervention and speeds up the delivery of new features and bug fixes.

By automating the testing and deployment processes, CI/CD not only enhances collaboration but also improves software quality by catching bugs early in the development cycle.

 

Cicd

 

How Do Pytest and Selenium Fit Into CI/CD?

Pytest is a popular Python testing framework that simplifies the process of writing tests. It’s known for its simplicity, scalability, and ease of integration with other tools. Selenium, on the other hand, is a powerful tool for automating web browsers, making it an ideal choice for testing web applications.

Together, Pytest and Selenium can be used to automate web testing, ensuring that every change made to the codebase is verified through browser-based tests before deployment.

Setting Up a Simple CI/CD Pipeline with Pytest and Selenium

To understand how Pytest and Selenium work together in CI/CD, let’s walk through the process.

  1. Writing Selenium Tests with Pytest:
    First, we need to write automated tests for our web application using Selenium. Here’s a simple example where we automate the process of checking the title of a webpage:

    import pytest
    from selenium import webdriver
    
    # Test case to check the title of a webpage
    def test_page_title():
        driver = webdriver.Chrome()
        driver.get("https://www.example.com")
        assert "Example Domain" in driver.title
        driver.quit()
    

    In this example, we’re using Selenium’s webdriver to launch a browser and navigate to a URL. Then, we assert that the page title contains the string “Example Domain”.

  2. Integrating Pytest into a CI Pipeline:
    Now that we have our Selenium tests, we need to integrate them into a CI/CD pipeline. Popular CI tools like Jenkins, GitHub Actions, or GitLab CI can be used to automate this process. For example, let’s look at how to integrate Pytest with GitHub Actions, a CI tool provided by GitHub. This will run the Selenium tests every time a code change is pushed to the repository. Here’s a simple yaml configuration for GitHub Actions:

    name: Selenium Tests CI
    
    on:
      push:
        branches:
          - main
    
    jobs:
      selenium-tests:
        runs-on: ubuntu-latest
        
        steps:
        - name: Checkout code
          uses: actions/checkout@v2
          
        - name: Set up Python
          uses: actions/setup-python@v2
          with:
            python-version: '3.x'
            
        - name: Install dependencies
          run: |
            pip install -r requirements.txt
            sudo apt-get install -y chromium-chromedriver
    
        - name: Run Selenium tests with Pytest
          run: |
            pytest tests/test_selenium.py --maxfail=1 --disable-warnings -q
    

    In this configuration:

      • The on: push section specifies that this pipeline should run whenever there’s a push to the main branch.
      • The jobs section defines the steps to run the tests. First, it checks out the code, sets up Python, installs dependencies, and then runs the Selenium tests with Pytest.

     

  3. Running the Tests Automatically:
    Once the CI pipeline is set up, every time a developer pushes code to the repository, the pipeline will automatically trigger and run the Selenium tests using Pytest. If all tests pass, the process will proceed to deployment. If a test fails, the pipeline will stop, and the developer will be notified to fix the issue before continuing. This level of automation ensures that the web application remains bug-free and stable as new features or fixes are added. Additionally, it reduces the risk of introducing defects into production.

 

Benefits of Using Pytest and Selenium in CI/CD

  • Early Bug Detection: Running automated tests after every code change helps catch bugs early, making it easier to fix them before they grow into bigger issues.
  • Faster Development Cycles: Automated tests in the CI pipeline mean that developers spend less time manually testing, allowing them to focus more on feature development.
  • Consistent Test Execution: Selenium allows you to simulate real-user interactions with a web browser, ensuring that the application functions correctly across different browsers and devices.
  • Continuous Feedback: Developers get instant feedback if a test fails, enabling quicker fixes and smoother collaboration within the team.

Conclusion

Incorporating Pytest and Selenium into a CI/CD pipeline automates the testing of web applications, ensuring high-quality software that is ready for deployment at all times. This combination helps developers focus on writing features while the CI/CD pipeline takes care of the testing, making it an invaluable part of the modern software development lifecycle.

By automating everything from testing to deployment, teams can deliver features faster, identify bugs early, and provide a more reliable user experience. If you haven’t already, it’s time to embrace the power of Pytest and Selenium in your CI/CD workflow!

Happy Testing!

 

]]>
https://blogs.perficient.com/2024/12/27/simplifying-ci-cd-with-pytest-and-selenium-for-web-automation-testing/feed/ 0 374401
Advanced Strategies for Effective Test Automation with PyTest and Selenium https://blogs.perficient.com/2024/12/24/advanced-strategies-for-effective-test-automation-with-pytest-and-selenium/ https://blogs.perficient.com/2024/12/24/advanced-strategies-for-effective-test-automation-with-pytest-and-selenium/#respond Tue, 24 Dec 2024 06:55:16 +0000 https://blogs.perficient.com/?p=373517

As your test automation skills grow, it’s crucial to implement advanced strategies that enhance the efficiency, reliability, and maintainability of your tests. In this post, we’ll explore several techniques that can help you optimize your test automation framework using PyTest and Selenium.

1 Hjpcblbvd8mpqaezzxwvgg

  1. Custom Test Suites and Tags:
    Organizing tests into custom suites and using tags can help you manage your tests better, especially as the number of test cases grows. This approach allows you to group tests based on their functionality or the features they cover, making it easier to run specific sets of tests as needed.Creating Custom Test Suites:
    You can create custom test suites by organizing your tests in directories and using PyTest’s built-in capabilities to run them selectively. For example, you can create a directory structure like this:
bash

/tests

    /smoke

        test_smoke.py

    /regression

        test_regression.py

    /features

        test_feature1.py

You can then run tests from a specific suite by pointing to that directory:

bash

pytest tests/smoke


Using Tags to Selectively Run Tests:

You can also use markers in PyTest to tag your tests. This allows you to run only tests with specific tags, making it easier to focus on certain areas of your application.

Example of Tagging Tests:

import pytest

@pytest.mark.smoke

def test_login():

    # Test logic here


@pytest.mark.regression

def test_data_processing():

Smoke Tests

To run only the smoke tests, you would use:

bash

pytest -m smoke

This selective execution can save time and resources, especially when working with a large test suite.

  1. Data-Driven Testing:
    Data-driven testing allows you to run the same test with multiple sets of data. This is particularly useful for testing forms, login scenarios, or any feature that requires varying input. You can use pytest.mark.parametrize to achieve this easily.Example of Data-Driven Testing:

    import pytest
    
    from pages.login_page import LoginPage
    
    @pytest.mark.parametrize("username, password, expected", [
    
        ("user1", "pass1", "Dashboard"),
    
        ("user2", "pass2", "Dashboard"),
    
        ("invalid_user", "wrong_pass", "Login Failed")
    
    ])
    
    def test_login(setup_browser, username, password, expected):
    
        driver = setup_browser
    
        login_page = LoginPage(driver)
    
        login_page.enter_username(username)
    
        login_page.enter_password(password)
    
        login_page.click_login()
    
        if expected == "Dashboard":
    
            assert login_page.is_login_successful(), f"Login failed for {username}"
    
        else:
    
            assert login_page.is_login_failed(), f"Expected login failure for {username}"
    

    This approach allows you to easily manage multiple test cases while keeping your code clean.

  2. Parallel Test Execution
    When you have a large suite of tests, running them sequentially can take a considerable amount of time. PyTest allows you to run tests in parallel using the pytest-xdist plugin, which can significantly reduce execution time.Installing pytest-xdist:

    bash
    
    pip install pytest-xdist


Running Tests in Parallel:

You can run your tests in parallel by simply using the -n option followed by the number of CPU cores you want to utilize:

bash

pytest -n 4

This command will execute your tests across four parallel processes, speeding up your testing process.

  1. Implementing Page Factory Pattern:
    The Page Factory pattern is an enhancement of the Page Object Model that provides a way to initialize elements more efficiently. By using the PageFactory class, you can reduce boilerplate code and improve readability.Example of Page Factory Implementation:

    from selenium.webdriver.support.page_factory import PageFactory
    
    class LoginPage:
    
        def __init__(self, driver):
    
            self.driver = driver
    
            self.username_field = PageFactory.init_elements(driver, "username")
    
            self.password_field = PageFactory.init_elements(driver, "password")
    
            self.login_button = PageFactory.init_elements(driver, "login")

    This pattern can help manage elements more effectively, especially in larger applications.

  2. Custom Assertions and Helper Methods
    Creating custom assertion methods can encapsulate common checks that you perform across multiple tests, promoting reusability and cleaner code. For example, you can create a base class for your tests that includes common assertions.Example of Custom Assertions:

    class BaseTest:
    
        def assert_title_contains(self, driver, text):
    
            assert text in driver.title, f"Expected title to contain '{text}', but got '{driver.title}'"
    
    class TestLogin(BaseTest):
    
        def test_login_success(self, setup_browser):
    
            driver = setup_browser
    
            login_page = LoginPage(driver)
    
            login_page.enter_username("valid_user")
    
            login_page.enter_password("valid_password")
    
            login_page.click_login()
    
            self.assert_title_contains(driver, "Dashboard")

    This approach enhances readability and allows for more sophisticated assertions.

  1. Continuous Integration (CI) Integration:
    Integrating your test automation suite with a CI tool (like Jenkins, Travis CI, or GitHub Actions) can automate your testing process. This ensures that tests are run automatically on every code change, providing immediate feedback to developers.

Basic CI Workflow:

  1. Push Code to Repository: When code is pushed to the repository, it triggers the CI pipeline.
  2. Run Tests: The CI tool executes your test suite using PyTest.
  3. Report Results: Test results are reported back to the developers, helping them identify issues quickly.

Conclusion

Implementing these advanced strategies in your PyTest and Selenium test automation framework can lead to significant improvements in efficiency, reliability, and maintainability. By utilizing custom test suites and tags, embracing data-driven testing, enabling parallel execution, applying the Page Factory pattern, creating custom assertions, and integrating with CI, you can build a robust testing framework that scales with your application.

As you refine your test automation practices, remember to keep exploring and adapting to new tools and techniques that can further enhance your workflow. Happy testing!

]]>
https://blogs.perficient.com/2024/12/24/advanced-strategies-for-effective-test-automation-with-pytest-and-selenium/feed/ 0 373517
Improving Selenium Test Stability with Pytest Retries and Waits https://blogs.perficient.com/2024/12/23/improving-selenium-test-stability-with-pytest-retries-and-waits/ https://blogs.perficient.com/2024/12/23/improving-selenium-test-stability-with-pytest-retries-and-waits/#respond Mon, 23 Dec 2024 13:25:57 +0000 https://blogs.perficient.com/?p=373506

Introduction

Flaky tests—those that fail intermittently—are a common headache for test automation teams. They can be especially frustrating in Selenium tests because of the dynamic nature of web applications. Elements might take time to load, page navigation could be slow, or JavaScript-heavy applications might delay interactions. These issues lead to false negatives in tests, where tests fail even though the application works fine.

In this blog, we’ll explore how to use Pytest retries and explicit/implicit waits to improve the stability of your Selenium tests and reduce flaky test failures.

Picture9

Why Selenium Tests Are Flaky

Flaky tests typically fail due to the following issues:

  • Dynamic Content: Elements that take time to load (like AJAX content) or slow-rendering pages.
  • Network Issues: Delays or failures in loading resources or API calls.
  • Timing Issues: Trying to interact with elements before they’re fully loaded or ready.

The key to reducing flaky tests lies in two techniques: retries and waits.

Using Pytest Retries for Flaky Tests with pytest-rerunfailures

A simple solution to mitigate flaky tests is to retry failed tests a certain number of times. The pytest-rerunfailures plugin allows you to automatically rerun tests that fail, thus reducing the impact of intermittent failures.

  1. Installation: Install the pytest-rerunfailures plugin:
    bash
    pip install pytest-rerunfailures
    
  2. Configuration: To enable retries, use the –reruns option when running your tests. For example, to retry a failed test 3 times, run:
    bash
    pytest --reruns 3
    

    You can also set the number of retries in your pytest.ini configuration file:

    ini
    
    [pytest]
    
    reruns = 3
    
    rerunsDelay = 2  #Delay between retries in seconds

     

  3. Example of Retries: Let’s say you have a test that clicks a button to submit a form. Sometimes, due to timing issues, the button might not be clickable. By adding retries, the test will automatically retry if the failure is due to a transient issue.
    def test_submit_button(mocker):
        # Simulate flaky behavior
        mocker.patch('selenium.webdriver.common.by.By.ID', return_value='submit')
        # Trigger a click action on the button
        button = driver.find_element_by_id('submit')
        button.click()
        assert button.is_enabled()  # Check button state
    

Using Waits to Ensure Elements Are Ready

In Selenium, waits are crucial to ensure that the elements you want to interact with are available and ready. There are two types of waits: implicit and explicit.

  1. Implicit Waits: Implicit waits instruct the WebDriver to wait a certain amount of time for elements to appear before throwing an exception.
    driver.implicitly_wait(10)  # Waits for 10 seconds for elements to load

    While easy to use, implicit waits can sometimes slow down tests and make debugging more difficult because they apply globally to all elements.

  2. Explicit Waits: Explicit waits are more powerful and precise. They allow you to wait for specific conditions before proceeding with interactions. WebDriverWait combined with expected conditions is commonly used.Example: Wait for an element to be clickable before clicking on it:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.element_to_be_clickable((By.ID, "submit_button")))
    element.click()
    
  3. Using Waits for AJAX Content: Often, web pages use AJAX to load content dynamically. Explicit waits are perfect for waiting until AJAX calls finish loading.
    # Wait until the AJAX content is visible
    wait.until(EC.visibility_of_element_located((By.ID, "ajax-content")))
    

Best Practices for Waits and Retries

  • Use explicit waits for better control: Explicit waits allow you to wait for specific conditions (like visibility or clickability), improving test reliability.
  • Combine retries with waits: Ensure that retries are only triggered after sufficient wait time to account for potential page load or element rendering delays.
  • Optimize test timing: Use waits for specific elements rather than using global implicit waits, which can slow down tests.

Conclusion

By using Pytest retries and explicit/implicit waits, you can significantly improve the stability of your Selenium tests. Retries help handle intermittent failures, while waits ensure that elements are ready before interacting with them. Together, these strategies reduce flaky test results, making your test suite more reliable and consistent. Happy Testing!

 

]]>
https://blogs.perficient.com/2024/12/23/improving-selenium-test-stability-with-pytest-retries-and-waits/feed/ 0 373506
Handling Complex Test Scenarios with Selenium and Pytest: Advanced Techniques https://blogs.perficient.com/2024/12/06/handling-complex-test-scenarios-with-selenium-and-pytest-advanced-techniques/ https://blogs.perficient.com/2024/12/06/handling-complex-test-scenarios-with-selenium-and-pytest-advanced-techniques/#respond Fri, 06 Dec 2024 10:18:55 +0000 https://blogs.perficient.com/?p=372988

In the world of test automation, Selenium paired with Pytest is a powerful combination. While basic web interactions can be automated easily, complex test scenarios often require advanced techniques. These scenarios may involve dealing with dynamic elements, multiple browser windows, interacting with iFrames, handling AJAX calls, or managing file uploads. In this blog, we will explore some advanced strategies to handle these complex situations, ensuring your tests are robust and reliable.

Selpython

Handling Dynamic Elements in Selenium

Web applications today are highly dynamic, often relying on JavaScript and AJAX to load or update content. Selenium can struggle with elements that appear or change dynamically on the page. Fortunately, explicit waits in Selenium can help you handle these situations.

Explicit Waits ensure the test waits until a specific condition is met before proceeding. This is crucial when interacting with dynamic elements that load after the page is rendered.

python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# Wait for an element to be visible
wait = WebDriverWait(driver, 10)
dynamic_element = wait.until(EC.visibility_of_element_located((By.ID, "dynamicElementId")))
dynamic_element.click()

Best Practice: Always use explicit waits for elements that load after page load or change state based on user interaction (e.g., buttons that become clickable after AJAX completion).

Working with iFrames

In modern web applications, iFrames (inline frames) embed content like videos, forms, or ads within a webpage. Selenium interacts with the main document by default, so interacting with elements inside iFrames requires special handling.

You must first switch to the frame to interact with elements inside an iFrame.

python
# Switch to an iFrame by index, name, or WebElement
driver.switch_to.frame(0)  # Switch to the first iFrame on the page

# Interact with elements inside the iFrame
button = driver.find_element_by_id("submit_button")
button.click()

# Switch back to the main document
driver.switch_to.default_content()

Best Practice: Always switch back to the default content after interacting with elements in an iFrame to avoid issues with subsequent commands.

Handling Multiple Windows or Tabs

You may often need to interact with multiple windows or tabs in web applications. Selenium manages this scenario by using window handles. When a new window or tab is opened, it gets a unique handle that you can use to switch between windows.

python
# Get the current window handle
main_window = driver.current_window_handle

# Perform actions that open a new window or tab
driver.find_element_by_id("open_window_button").click()

# Get all window handles and switch to the new window
all_windows = driver.window_handles
for window in all_windows:
    if window != main_window:
        driver.switch_to.window(window)
        break

# Interact with the new window
driver.find_element_by_id("new_window_element").click()

# Switch back to the main window
driver.switch_to.window(main_window)

Best Practice: Always store the handle of the main window before switching to new windows or tabs to easily return after finishing the tasks in the new window.

Handling AJAX Requests

AJAX (Asynchronous JavaScript and XML) calls are often used to load data dynamically without reloading the entire page. However, this can complicate testing, as Selenium might try to interact with elements before completing the AJAX request.

To handle AJAX calls efficiently, we use explicit waits in conjunction with conditions that ensure the page has fully loaded or the necessary AJAX requests are completed.

python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait until an AJAX request is complete (e.g., waiting for an element to be visible after AJAX content loads)
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.ID, "ajax_loaded_element")))

Best Practice: Use explicit waits for specific AJAX elements to load before interacting with them. Avoid using implicit waits globally, as they can slow down your tests.

File Uploads with Selenium

File uploads are a frequent requirement in many web applications, such as submitting a form with a file attachment. In Selenium, you can interact with file input elements using the send_keys() method to upload a file directly.

python
file_input = driver.find_element_by_id("file_upload")
file_input.send_keys("/path/to/file.txt")

Best Practice: Ensure the file path is correct and test in different environments to handle scenarios where file paths may vary.

Taking Screenshots for Debugging

During test execution, capturing screenshots is crucial to help debug failures. Selenium allows you to capture screenshots at any point during the test.

python
driver.get_screenshot_as_file('screenshot.png')

Best Practice: Take screenshots after each test step or on failure to capture the application’s state, making it easier to debug issues.

Data-Driven Testing with Pytest

Handling multiple input data sets in tests is essential, especially when you want to run the same test with different sets of inputs. With Pytest, you can utilize fixtures or parametrize to pass other data sets to the test function.

python
import pytest

@pytest.mark.parametrize("username, password", [("user1", "pass1"), ("user2", "pass2")])
def test_login(username, password):
    driver.get("http://example.com/login")
    driver.find_element_by_id("username").send_keys(username)
    driver.find_element_by_id("password").send_keys(password)
    driver.find_element_by_id("login_button").click()
    assert "Welcome" in driver.page_source

Best Practice: Use parametrize to run the same test with different data inputs. It ensures your tests are comprehensive and reduces the need for repetitive code.

Conclusion

Handling complex test scenarios requires a combination of the right tools and techniques. Selenium and Pytest offer powerful mechanisms to tackle dynamic elements, iFrames, multiple windows, AJAX requests, and more. You can create more robust, reliable, and efficient test automation solutions by mastering these advanced techniques.

When working with dynamic and complex applications, always ensure that you are leveraging Selenium’s full capabilities—like waits, window handles, and file uploads—while using Pytest to manage test data, structure tests, and handle failures efficiently. This will help you automate tests effectively and maintain quality across complex applications.

 

]]>
https://blogs.perficient.com/2024/12/06/handling-complex-test-scenarios-with-selenium-and-pytest-advanced-techniques/feed/ 0 372988
Using PyTest with Selenium for Efficient Test Automation https://blogs.perficient.com/2024/11/04/using-pytest-with-selenium-for-efficient-test-automation/ https://blogs.perficient.com/2024/11/04/using-pytest-with-selenium-for-efficient-test-automation/#respond Mon, 04 Nov 2024 06:47:49 +0000 https://blogs.perficient.com/?p=370819

In our previous post, we explored the basics of Selenium with Python, covering the introduction, some pros and cons, and a basic program to get you started. In this post, we’ll delve deeper into the world of test automation by integrating Selenium with PyTest, a popular testing framework in Python. PyTest makes it easier to write simple and scalable test cases, which is crucial for maintaining a robust test suite.

Picture9

What is PyTest?

PyTest is a testing framework that allows you to write simple yet scalable test cases. It is widely used due to its easy syntax, powerful features, and rich plugin architecture. PyTest can run tests, handle setup and teardown, and integrate with various other tools and libraries.

Why Use PyTest with Selenium?

  • Readable and Maintainable Tests: PyTest’s syntax is clean and concise, making tests easier to read and maintain.
  • Powerful Assertions: PyTest provides powerful assertion introspection, which gives more detailed error messages.
  • Fixtures: PyTest fixtures help in setting up preconditions for your tests and can be reused across multiple test functions.
  • Extensible: PyTest’s plugin architecture allows for easy extension and customization of test runs.

Setting Up PyTest with Selenium

Prerequisites

Before you begin, ensure you have the following installed:

  • Python (>= 3.6)
  • Selenium (pip install selenium)
  • PyTest (pip install pytest)

You also need a WebDriver for the browser you intend to automate. For instance, ChromeDriver for Google Chrome.

Basic Test Setup

  • Project Structure

Create a directory structure for your test project:

Picture1

  • Writing Your First Test

In the test_example.py file, write a simple test case:

This simple test opens Google and checks if the page title contains “Google”.

Picture2

  • Using PyTest Fixtures

Fixtures in PyTest are used to manage setup and teardown. Create a fixture in the conftest.py file:

Picture3

Now, update the test to use this fixture:

Picture4

This approach ensures that the WebDriver setup and teardown are handled cleanly.

  • Running Your Tests

To run your tests, navigate to the project directory and use the following command:

Picture7

PyTest will discover and run all the test functions prefixed with test_.

Advanced Usage

  • Parameterized Tests

You can run a test with different sets of data using @pytest.mark.parametrize:

Picture5

  • Custom PyTest Plugins

Extend PyTest functionalities by writing custom plugins. For example, you can create a plugin to generate HTML reports or integrate with CI/CD tools.

  • Headless Browser Testing

Run tests in headless mode to speed up execution:

Picture6

Conclusion

Integrating PyTest with Selenium not only enhances the readability and maintainability of your tests but also provides powerful features to handle complex test scenarios. By using fixtures, parameterization, and other advanced features, you can build a robust and scalable test suite.

In the next post, we will explore the Page Object Model (POM) design pattern, which is a crucial technique for managing large test suites efficiently.

 

]]>
https://blogs.perficient.com/2024/11/04/using-pytest-with-selenium-for-efficient-test-automation/feed/ 0 370819
Selenium – Uploading a File Using Robot Class https://blogs.perficient.com/2024/10/09/selenium-uploading-a-file-using-robot-class/ https://blogs.perficient.com/2024/10/09/selenium-uploading-a-file-using-robot-class/#respond Wed, 09 Oct 2024 07:19:35 +0000 https://blogs.perficient.com/?p=370173

Need For Robot Class:

Selenium normally allows file uploads using the send Keys () method for file input fields. However, if the input field is not of type “file,” it might run into problems and here comes the Robot class.

The Robot class, part of the java.awt package, helps you perform system-level events, pressing keys, moving the cursor, and clicking. This makes it a powerful tool, especially when you need to interact with system-level components that Selenium alone cannot handle.

 

When is the Robot Class Suitable for File Uploads?

Use the Robot class for file uploads in cases where:

  • The file input field is hidden or otherwise inaccessible.
  • The input field is not of type “file,” meaning send Keys () cannot be used.
  • The file upload dialog is customized and does not respond to standard Selenium commands.

How to perform a file upload operation through the Robot Class?

Precondition: Whenever we use the press method, we must also use the release method. If the release method is not used, the keyboard press action will remain active. To stop the pressing action, the release method must be invoked.

Now, let’s look at a step-by-step example of how to upload a file using the Robot class.

  1. Trigger the File Upload Dialog
    First, navigate to the page where you need to upload the file. Click the button that opens the file chooser dialog.
  2. Use the Robot Class to Interact with the Dialog
    After the dialog opens, use the Robot class to input the file path and handle the upload process through simulated keyboard events.

Here’s an example of Java code that demonstrates this process.

 

Code Scr 2

 

Explanation of the Code:

  1. Trigger the File Upload Dialog 
    The first step is locating the upload button using Selenium’s FindElement() method and clicking it to open the file upload dialog.
  2. Simulating Keyboard Actions Using the Robot Class
    • Create a Robot object to simulate the required keyboard actions.
    • Use String Selection and Toolkit to copy the file path to the clipboard.
    • The Robot class then simulates pressing Ctrl + v to paste the file path into the file chooser.
    • Finally, simulate pressing the Enter key to upload the file.
  3. Adding Delays
    Delays between actions ensure that each step is completed before moving on to the next, which helps to avoid timing issues.

Final Thoughts:

Pros of Robot Class:

  • Simulates keyboard and mouse actions easily.
  • Can handle pop-ups and system-level tasks.
  • Useful for automating tasks outside of the browser.

Cons of Robot Class:

  • Limited to basic interactions (no complex web actions).
  • Difficult to test dynamic web elements.
  • Not ideal for cross-browser testing.

When facing challenges with hidden input fields or custom dialogs, consider using the Robot class in your automation strategy.

For more information, you can refer to this website: https://www.guru99.com/using-robot-api-selenium.htmlConclusion

 

Similar tools:

  1. AutoIt https://www.autoitscript.com/site/

  2. Sikuli – https://www.sikuli.org/

  3. AWT Event Queue (Java) – https://docs.oracle.com/javase/7/docs/api/java/awt/EventQueue.html

]]>
https://blogs.perficient.com/2024/10/09/selenium-uploading-a-file-using-robot-class/feed/ 0 370173
Encrypting and Decrypting Passwords Using Java in Selenium https://blogs.perficient.com/2024/07/29/encrypting-and-decrypting-passwords-using-java-in-selenium/ https://blogs.perficient.com/2024/07/29/encrypting-and-decrypting-passwords-using-java-in-selenium/#respond Mon, 29 Jul 2024 11:02:43 +0000 https://blogs.perficient.com/?p=366370

Security is a crucial aspect of any application, especially when dealing with sensitive information such as passwords. Storing passwords in plain text can expose them to potential security risks. In this blog, we’ll discuss how to securely encrypt and decrypt passwords in Java and how to integrate this functionality into your Selenium automation scripts.

Why Encrypt Passwords?

Encrypting passwords ensures that they are stored in an unreadable format, reducing the risk of unauthorized access. Even if someone gains access to the stored data, encrypted passwords remain secure unless the encryption key is compromised.

Prerequisites

Before we begin, ensure you have the following:

  • Java Development Kit (JDK) installed.
  • Selenium WebDriver library added to your project.
  • Basic understanding of Java and Selenium.

 

Setting Up Encryption and Decryption

We’ll use the javax.crypto package in Java, which provides the necessary classes for encryption and decryption. We’ll create two classes: EncryptionHelper for handling encryption and decryption, and SeleniumTest to demonstrate the integration with Selenium.

 

Step 1: Create the EncryptionHelper Class

This class contains methods to generate a secret key, encrypt a password, and decrypt a password.

Import Necessary Packages

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import java.util.Base64;

 

Define the EncryptionHelper Class

public class EncryptionHelper {

    private static final String ALGORITHM = "AES"; // Algorithm for encryption

    // Generate a secret key

    public static SecretKey generateKey() throws Exception {

        KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);

        keyGen.init(128); // Key size can be 128, 192, or 256 bits

        return keyGen.generateKey();

    }


    // Encrypt the password

    public static String encrypt(String password, SecretKey key) throws Exception {

        Cipher cipher = Cipher.getInstance(ALGORITHM);

        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] encryptedPassword = cipher.doFinal(password.getBytes());

        return Base64.getEncoder().encodeToString(encryptedPassword);

    }


    // Decrypt the password

    public static String decrypt(String encryptedPassword, SecretKey key) throws Exception {

        Cipher cipher = Cipher.getInstance(ALGORITHM);

        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] decodedPassword = Base64.getDecoder().decode(encryptedPassword);

        byte[] originalPassword = cipher.doFinal(decodedPassword);

        return new String(originalPassword);

    }

}

 

Explanation

  • generateKey(): Generates a secret key using the AES algorithm.
  • encrypt(): Encrypts the given password using the secret key.
  • decrypt(): Decrypts the given encrypted password using the secret key.

 

Step 2: Create the SeleniumTest Class

This class demonstrates how to use the EncryptionHelper class to encrypt and decrypt passwords within a Selenium script.

 

Import Necessary Packages

import javax.crypto.SecretKey;

 

Define the SeleniumTest Class

public class SeleniumTest {

    public static void main(String[] args) {

        try {

            // Generate a secret key

            SecretKey secretKey = EncryptionHelper.generateKey();


            // Original password
            String originalPassword = "password@123";


            // Encrypt the password
            String encryptedPassword = EncryptionHelper.encrypt(originalPassword, secretKey);

            System.out.println("Encrypted Password: " + encryptedPassword);


            // Decrypt the password
            String decryptedPassword = EncryptionHelper.decrypt(encryptedPassword, secretKey);

            System.out.println("Decrypted Password: " + decryptedPassword);


        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

 

Explanation

  • generateKey(): Generates a secret key for encryption and decryption.
  • encrypt(): Encrypts the original password.
  • decrypt(): Decrypts the encrypted password back to its original form.

 

Output:

2024 07 25 15 55 09 Eclipse Workspace Seleniumframework Src Practice Seleniumtest.java Eclipse I

Integrating Encryption with Selenium

To demonstrate the integration of password encryption with a Selenium test, we will extend the SeleniumTest class to include a simple login automation script.

Import Selenium Packages

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

 

Update the SeleniumTest Class

public class SeleniumTest {

    public static void main(String[] args) {

        try {

            // Generate a secret key

            SecretKey secretKey = EncryptionHelper.generateKey();


            // Original password
            String originalPassword = "password@123";


            // Encrypt the password
            String encryptedPassword = EncryptionHelper.encrypt(originalPassword, secretKey);

            System.out.println("Encrypted Password: " + encryptedPassword);


            // Decrypt the password
            String decryptedPassword = EncryptionHelper.decrypt(encryptedPassword, secretKey);

            System.out.println("Decrypted Password: " + decryptedPassword);


            // Set up WebDriver
            System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

            WebDriver driver = new ChromeDriver();


            // Navigate to the login page
            driver.get("https://example.com/login");


            // Find username and password fields
            WebElement usernameField = driver.findElement(By.id("username"));

            WebElement passwordField = driver.findElement(By.id("password"));


            // Enter username and decrypted password
            usernameField.sendKeys("myUsername");

            passwordField.sendKeys(decryptedPassword);


            // Submit the login form
            WebElement loginButton = driver.findElement(By.id("loginButton"));

            loginButton.click();


            // Close the browser
            driver.quit();


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

 

Advantages of Encrypting Passwords

  1. Security: Encrypting passwords ensures that they are not stored in plain text, reducing the risk of unauthorized access.
  2. Data Protection: Even if the encrypted passwords are exposed, they remain secure without the decryption key.
  3. Compliance: Helps in complying with security standards and regulations that mandate encryption of sensitive data.

Conclusion

Encrypting and decrypting passwords in Java is a straightforward process that significantly enhances the security of your application. By integrating this functionality into your Selenium scripts, you can ensure that sensitive data, such as passwords, is handled securely. Follow the steps outlined in this blog to implement password encryption and decryption in your projects, and enjoy the peace of mind that comes with enhanced security.

]]>
https://blogs.perficient.com/2024/07/29/encrypting-and-decrypting-passwords-using-java-in-selenium/feed/ 0 366370
Understanding Encryption Algorithms: AES, DES, and Blowfish https://blogs.perficient.com/2024/07/29/understanding-encryption-algorithms-aes-des-and-blowfish/ https://blogs.perficient.com/2024/07/29/understanding-encryption-algorithms-aes-des-and-blowfish/#respond Mon, 29 Jul 2024 11:02:19 +0000 https://blogs.perficient.com/?p=366375

In our previous blog, we discussed how to encrypt and decrypt passwords in Java using the AES algorithm. In this follow-up post, we’ll delve deeper into various encryption algorithms, specifically AES, DES, and Blowfish. We’ll explain each algorithm in detail and provide code examples for their implementation.

 

Types of Encryption Algorithms

  1. AES (Advanced Encryption Standard)

AES is a symmetric encryption algorithm widely used across the globe. It was established by the U.S. National Institute of Standards and Technology (NIST) in 2001. AES encrypts data in blocks of 128 bits using keys of 128, 192, or 256 bits.

Key Features:

  • Symmetric Key Algorithm: The same key is used for both encryption and decryption.
  • Block Cipher: Encrypts data in fixed-size blocks (128 bits).
  • Highly Secure: Resistant to all known cryptographic attacks.

 

AES Code Example:

public class AesEncryptionHelper {

private static final String ALGORITHM = "AES";

// Generate a secret key

public static SecretKey generateKey() throws Exception {

KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);

keyGen.init(128);

return keyGen.generateKey();

}

// Encrypt the password

public static String encrypt(String password, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] encryptedPassword = cipher.doFinal(password.getBytes());

return Base64.getEncoder().encodeToString(encryptedPassword);

}

// Decrypt the password

public static String decrypt(String encryptedPassword, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] decodedPassword = Base64.getDecoder().decode(encryptedPassword);

byte[] originalPassword = cipher.doFinal(decodedPassword);

return new String(originalPassword);

}

}

 

Output

Aes

 

  1. DES (Data Encryption Standard)

DES is an older symmetric-key algorithm developed in the 1970s. It uses a 56-bit key to encrypt data in 64-bit blocks. Although DES was once a widely adopted standard, it is now considered insecure due to its small key size, which is vulnerable to brute-force attacks.

Key Features:

  • Symmetric Key Algorithm: The same key is used for both encryption and decryption.
  • Block Cipher: Encrypts data in fixed-size blocks (64 bits).
  • Outdated Security: Vulnerable to brute-force attacks due to the small key size.

 

DES Code Example:

public class DesEncryptionHelper {

private static final String ALGORITHM = "DES";

// Generate a secret key

public static SecretKey generateKey() throws Exception {

KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);

keyGen.init(56);

return keyGen.generateKey();

}

// Encrypt the password

public static String encrypt(String password, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] encryptedPassword = cipher.doFinal(password.getBytes());

return Base64.getEncoder().encodeToString(encryptedPassword);

}

// Decrypt the password

public static String decrypt(String encryptedPassword, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] decodedPassword = Base64.getDecoder().decode(encryptedPassword);

byte[] originalPassword = cipher.doFinal(decodedPassword);

return new String(originalPassword);

}

}

 

Output:

Des

  1. Blowfish

Blowfish is a symmetric-key block cipher designed by Bruce Schneier in 1993. It uses a variable-length key from 32 bits to 448 bits, making it flexible and secure. Blowfish is known for its speed and effectiveness and is used in various encryption products.

Key Features:

  • Symmetric Key Algorithm: The same key is used for both encryption and decryption.
  • Block Cipher: Encrypts data in fixed-size blocks (64 bits).
  • Flexible Key Length: Supports key lengths from 32 bits to 448 bits.

 

Blowfish Code Example:

public class BlowfishEncryptionHelper {

private static final String ALGORITHM = "Blowfish";

// Generate a secret key

public static SecretKey generateKey() throws Exception {

KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);

keyGen.init(128); // Key size can be from 32 to 448 bits

return keyGen.generateKey();

}

// Encrypt the password

public static String encrypt(String password, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] encryptedPassword = cipher.doFinal(password.getBytes());

return Base64.getEncoder().encodeToString(encryptedPassword);

}

// Decrypt the password

public static String decrypt(String encryptedPassword, SecretKey key) throws Exception {

Cipher cipher = Cipher.getInstance(ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);

byte[] decodedPassword = Base64.getDecoder().decode(encryptedPassword);

byte[] originalPassword = cipher.doFinal(decodedPassword);

return new String(originalPassword);

}

}

 

Output:

Blowfish

Comparing AES, DES, and Blowfish

Feature AES DES Blowfish
Key Length 128, 192, or 256 bits 56 bits 32 to 448 bits
Block Size 128 bits 64 bits 64 bits
Security Highly secure Insecure (vulnerable) Secure with flexible key
Performance Fast and efficient Slower due to smaller key Fast and flexible
Adoption Widely adopted Largely obsolete Used in various products

 

Conclusion

Understanding different encryption algorithms is essential for choosing the right one for your application’s security needs. AES, DES, and Blowfish each have their strengths and weaknesses. AES is highly secure and widely adopted, DES is outdated and insecure, while Blowfish offers flexibility in key length and is known for its speed.

]]>
https://blogs.perficient.com/2024/07/29/understanding-encryption-algorithms-aes-des-and-blowfish/feed/ 0 366375
AI Toolkits Magic: Automating CAPTCHA Recognition Using OpenCV and Tesseract https://blogs.perficient.com/2024/07/08/ai-toolkits-magic-automating-captcha-recognition-using-opencv-and-tesseract/ https://blogs.perficient.com/2024/07/08/ai-toolkits-magic-automating-captcha-recognition-using-opencv-and-tesseract/#comments Mon, 08 Jul 2024 05:31:18 +0000 https://blogs.perficient.com/?p=365295

OpenCV and Tesseract can be associated with Artificial Intelligence due to their involvement in tasks that often fall under the AI umbrella, such as computer vision and text recognition. To automate solving image CAPTCHAs using Java, you will typically need several dependencies for tasks such as image processing, machine learning, and possibly computer vision.

OpenCV: A powerful library for computer vision and image processing. You can use the Java bindings for OpenCV.

Tesseract OCR: Tesseract OCR is an optical character recognition library that extracts text from images.

OpenCV (Open-Source Computer Vision Library)

  • Category: AI Toolkit for Computer Vision and Image Processing.
  • Purpose: Provides comprehensive tools for image and video processing, essential for many AI applications.
  • Capabilities: Includes image transformation, filtering, feature detection, object detection, and support for machine learning and deep learning.
  • Usage: Commonly used in AI projects for tasks like object detection, face recognition, and image classification.

Tesseract

  • Category: AI Toolkit for Optical Character Recognition (OCR)
  • Purpose: Converts images of text into machine-readable text using machine learning techniques.
  • Capabilities: Recognizes and extracts text from images, supporting multiple languages and fonts.
  • Usage: Utilized in AI projects for tasks such as document digitization, data extraction from scanned documents, and integrating text recognition into applications.

Step 1: Set up Dependencies

First, add the necessary dependencies to your pom.xml file:

Opencv dependencies

Tesseract dependencies

Step 2: Write the Java Code

Create a Java class to preprocess the CAPTCHA image and extract the text using Tesseract.

Captchasolver Code for image captcha

Step 3: Set up Tesseract Data

You must create your Tesseract data files and place them in a project directory (e.g., tessdata). but you do need at least the data file for the language used in the CAPTCHA. Tesseract uses trained data files (often referred to as “language data” or “Tessdata”) to recognize text in different languages.

For example, you only need the English-trained data file if your CAPTCHA contains English text. If contains text in another language, you’ll need the corresponding trained data file.

Step 4: Run the code

Ensure you have an image CAPTCHA in your project directory(e.g.,captcha//captcha.png) and adjust the paths in the code accordingly.

Captcha image under folder

Then, run the CaptchaSolver class.

Final Console Output of Extracted Image Text

Output of code

Explanation

  1. Image Preprocessing:
    • Load the image in grayscale mode.
    • Apply a binary threshold to convert the image to black and white.
    • Save the preprocessed image to disk.
  2. Text Extraction with Tesseract:
    • Initialize Tesseract and point it to the tessdata directory.
    • Process the preprocessed image with Tesseract to extract the text.

By running this code, you should be able to automate the solving of simple image CAPTCHAs. Adjust the preprocessing steps as necessary for more complex CAPTCHAs.

Summary

Referring to OpenCV and Tesseract as components of an “AI toolkit” accurately reflects their roles in enabling and enhancing AI applications, particularly in the domains of computer vision and text recognition. They are essential tools for implementing AI-driven solutions, making them integral parts of the AI development ecosystem.

]]>
https://blogs.perficient.com/2024/07/08/ai-toolkits-magic-automating-captcha-recognition-using-opencv-and-tesseract/feed/ 1 365295
Streamlining Web Automation: A Comprehensive Guide to Using AutoIT with Selenium https://blogs.perficient.com/2024/02/27/streamlining-web-automation-a-comprehensive-guide-to-using-autoit-with-selenium/ https://blogs.perficient.com/2024/02/27/streamlining-web-automation-a-comprehensive-guide-to-using-autoit-with-selenium/#respond Wed, 28 Feb 2024 05:10:46 +0000 https://blogs.perficient.com/?p=357125

In the realm of web automation, handling various scenarios like file upload, file download, and various Windows GUI operations can be challenging. AutoIt, a powerful scripting language and automation tool, seamlessly integrates with Selenium to tackle these challenges. This blog provides a detailed guide on installing and configuring AutoIT and demonstrates its usage with Selenium for file upload and file download.

What is AutoIT?

AutoIT is a scripting language primarily designed for automating the Windows graphical user interface (GUI) and general scripting. It provides a simple scripting language with powerful automation capabilities, making it ideal for automating repetitive tasks, interacting with GUI elements, and handling various Windows-based operations.

Below are some of the applications in Selenium and Testing:

  • Handling Dialogs
  • File Upload/ File Download
  • GUI Testing
  • Window Management

Installing AutoIT

  1. Download AutoIt: Visit the official AutoIT website https://www.autoitscript.com/site/autoit/downloads/ and download the AutoIT installer.
  2. Install AutoIt: Run the downloaded installer, select x86(default) while installing, also keep others as default. Ensure that you install both AutoIt and AutoIT Editor.
  3. After installation: SciTE(AutoIT editor) .exe file will be present at location “C:\Program Files (x86)\AutoIt3\SciTE” and Au3Info_x64 (Spy tool) at “C:\Program Files (x86)\AutoIt3”

Using AutoIT with Selenium: File Upload

For instance, we want to perform some test that involves uploading a file from the local system on the page. A Windows dialog box will open to select the file from the local system to upload, due to the limitation of Selenium, there is no direct method to interact with the Windows application dialog box. Here comes the role of AutoIt which helps to perform such types of actions.

How to Upload a File with AutoIT and Selenium

Follow the below steps to upload a file on a website or application from the local system:

  1. Open Au3Info_x64 (Spy tool) and SciTE(AutoIT editor).
  2. Open the page where you want to upload a file; on clicking the upload button, the upload window dialog box opens.
  3. Using the spy tool, drag and drop the “FinderTool” icon on the “File Name” box.Spytool Findertool
  4. Note down the element’s Title and Control ID (Class+Instance) (File Name box).Title And Control Id
  5. Repeat the step for the next element i.e. “Open” Button and note down the title and Control ID.
  6. Now, open the Editor, and we will write the script that defines the steps to perform. We are using the Control Commands here; we can also use Window commands. The below image shows the script:Editor Script
  7. Syntax Explanation:
    • ControlFocus(“Title”, “text(optional)”, “Control ID”): To focus on an element using the title and control id.
    • ControlSetText(“Title”, “text(optional)”, “Control ID”, “new Text to enter”): To enter text in the selected element.
    • ControlClick(“Title”, “text(optional)”, “Control ID”): To click on an element.
    • You can refer to the documentation for more details: https://www.softwaretestinghelp.com/handle-windows-pop-up-in-selenium-using-autoit/
  8. Save the file with the ‘.au3’ extension > right-click the file and select Compile(x86) > ‘.exe’ file will be created.
  9. Now write the Selenium script to perform the test that requires the file upload action. We are navigating to the page > clicking the upload button > Running the AutoIt script .exe file to enter the path of the image and clicking on the open button. Below is the script:
    public class FileUpload {
        public static void main(String[] args) throws InterruptedException, IOException {
            
            //chrom driver automatically 
            WebDriverManager.chromedriver().setup();
            WebDriver driver  = new ChromeDriver();
            driver.manage().window().maximize();
            
            //Upload file
            //go to page and click on upload options
            driver.get("https://www.TestPage.com/jpg-to-pdf");
            driver.findElement(By.cssSelector("a[class*='upload-btn'] span[class='btn-label']")).click();
            
            //Execute the .exe file using java methods 
            Thread.sleep(3000);
            Runtime.getRuntime().exec("C:\\mohUploadsc.exe");
          }
    }
    
  10. Finally, run the script

We achieved the file upload operation with this integration of selenium and AutoIt.

Conclusion

AutoIT offers seamless integration with Selenium, enabling testers to easily handle complex scenarios like file upload/download, automating the Windows GUI, and general-purpose scripting. Following this guide can enhance your web automation capabilities and streamline your testing process. You can also find articles to read more about various applications of AutoIt in testing. Stay tuned for more insights on advanced web testing techniques! Happy Testing!

]]>
https://blogs.perficient.com/2024/02/27/streamlining-web-automation-a-comprehensive-guide-to-using-autoit-with-selenium/feed/ 0 357125