DEV Community

sunmathi
sunmathi

Posted on

1.Python Selenium Architecture 2.Significance of Python Virtual Environment 3.Examples of Python Virtual Environment

       ## 1.Python Selenium Architecture
Enter fullscreen mode Exit fullscreen mode

Selenium is a popular open-source framework used for automating web browser interactions.It is widely used for web applications.The architecture of selenium is designed to support a variety of browsers and programming language making it highly flexible and powerful.Here is detailed explanation of selenium architecture.

Selenium Components:-

Selenium has been in the industry for the long time and used by automation testers all around the globe.here are four major components of selenium as follows
   1.Selenium IDE
   2.Selenium Remote Control(RC)
   3.Selenium WenDriver
   4.Selenium Grid
Enter fullscreen mode Exit fullscreen mode

1.Selenium IDE:-

Selenium IDE serves as an innovative toolkit for web testing allowing users to record interactions with web applications.Selenium IDE was initially created by "Shinya Kasatani" in 2006.SeleniumIDE also helps to simplify the testing process.It is a friendly space for testers and developers to team up. This helps everyone quickly share important testing information and results,making things work better and feel accomplished.

IDE-Integrated Development Environment,It is nothing but a simple web browser extension.We just need to download and install the extension for that particular web browser

It can automate as well as record the entire automation process.people generally prefer to write test-scripts using python,java,javascripts etc.

Features of Selenium IDE:-

Record - With Selenium IDE users can record how they use a web application
PlayBack - Selenium IDE automatically repeats what you recorded earlier
Browser check - Selenium IDE works on various browsers for testing.
Check Elements - Users can easily look at different parts of a webpage and setup how to work with them
Spotting Errors - Selenium IDE helps users find and fix issues in their automated tests one step at a time.
Exporting Tests - We can save tests created in Selenium IDE in different programming languages(like java,python or c#).This lets you use them with other selenium tools.

**2.Selenium Remote Control(RC):-**

 Selenium RC was one of the earliest selenium tools proceding webdriver.It allowed testers to write automated web application tests in various programming languages like java,python,c#,etc.The key feature of selenium Rc was its ability to interact with web browsers using a server which acted as an intermediary between the testing code and the browser.
Enter fullscreen mode Exit fullscreen mode

It has been deprecated and not used these days.It is been replaced selenium webdriver or better to say the python selenium webdriver manager.
Web Driver is often considered the better choice over selenium Rc for several reasons are follows:
Improved API - WebDrivers offers a more straight forward and intuitive API compared to Selenium RC making it easier for developers and testers to write and maintain automated tests.
Better Performance - Web Driver interacts directly with the browsers bypassing the need for an intermediary server like Selenium RC which leads to faster test execution and improved performance.
Support for modern web technologies - Webdriver has better support for modern web technologies such as HTML5,CSS3 and javascript frameworks ensuring compatibilty with the latest web applications.

        **Selenium WebDriver:-**
Enter fullscreen mode Exit fullscreen mode

Selenium WedDriver is a robust open-source framework for automating web browsers primarily aimed at easing the testing and verification of web applications.As an important part of the selenium suite is WebDriver offers a programming interface to interact with web browsers allowing developers and testers to automate browser actions seamlessly.
It is a major component of selenium test suite.It provides as an interface between the programming language and the web-browser itself.

       **Selenium WedDriver Architecture:-**
Enter fullscreen mode Exit fullscreen mode

The architecture of selenium webdriver consists of the following components
Selenium Client Library -
They are language binding commands which you will use to write your automation scripts.This Libraries are available in different prgramming languages.They provide an interface to write test scripts.when a test script is executed it sends commands to the browser driver via JSON over HTTP.
This commands are compatible with HTTP,TCP-IP protocols.
They are nothing but wrappers which send the script commands to the network for execution into a web browser.

Selenium API _-
It is a set of rules which our python program uses to communicate with each other.
It helps us in automation without the need for the user to understand what is happening in the background.
_JSON Wire protocol
-
The commands that you write gets converted into JSON which is then transmitted across the network or to your web browser so that it can be executed for automation and testing.Commands are sent in JSON format over HTTP
The JSON requests are sent to the client using the HTTP protocol.

Browser Driver -
It acts as a bridge between the selenium scripts,libraries and web browser. It helps us to run the Selenium test scripts which comprises selenium commands on a particular web browser
Each browser has a corresponding driver that translate that translate the commands from the webdriver API into actions in the browser:
ChromeDriver for google chrome
GeckoDriver for Mozilla firefox
SafariDriver for safari
IEDriver for Internet Explorer
EdgeDriver for MicrosoftEdge

Core Components -
Web Driver is the core component of selenium and interacts directly with the web browser.It provides a programming interface to create and executes test scripts.WebDriver drives the browser the same way as a real user world.
Language Support -
WebDriver supports multiple programming Languages including java,c#,python,Ruby and JavaScript.

Browsers-
The browsers are the target environments where the testers are executed.WebDriver interacts with the browsers to perform the desired actions like clicking,typing and navigating,etc.

      **Workflow:-**
Enter fullscreen mode Exit fullscreen mode

Here is a step by step workflow of how selenium WebDriver works

Test Script Execution :
The user writes the test scripts using a selenium client library in their preferred programming.
The script is executed and commands are sent to the webdriver.

Command Transformation :
The client library converts the commands into JSON format and sends them via HTTP to the corresponding browser driver.

Driver Interaction:
The browser drivers receives the commands and translates them into browser specific actions.
The driver user browser specific mechanisms to execute these commands in the browser.

       **Browser Interaction** :

The browser performs the actions as instructed by the driver(e.g-clicking a button,entering text).
The browser responds back to the driver with the results of the executed actions.
Enter fullscreen mode Exit fullscreen mode

Result Translation :
The browser results sends the results back to the client library in JSON format.
The client library processes the results and presents them to the user.

       **Example:Python SeleniumWebDriver:-**

Here is simple example of how selenium webdriver can be used with python to open a browser and navigate to a website
Enter fullscreen mode Exit fullscreen mode

from selenium import webdriver
from selenium.wedriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep

class Example:
def_init_(self,url):
self.url=url
self.driver= webdriver.Chrome(service=Service(ChromeDriverManager.install()))

def using_chrome_browse(self):
    self.driver.maximize_window()
    self.driver.get(self.url)


def shut_down(self):
    self,driver.close()
Enter fullscreen mode Exit fullscreen mode

url = "http://www.guvi.in"
example=Example(url)
example.using_chrome_browser()
`

Features of Selenium Web Driver:

 features of selenium web driver are as follows,
Enter fullscreen mode Exit fullscreen mode

Direct Communication with Browsers- Unlike selenium RC WebDriver interacts directly with the browsers native support for automation leading to more stable and reliable testing.
Support for parallel Execution - WebDrivers allows for parallel test execution enabling faster test cycles and efficient utilization of resources.
Rich sets of API - Web Driver provides a comprehensive set of API's for navigating through web pages interacting with web elements,managing windows,handling alerts,etc.

             **Selenium Grid:-**

Selenium Grid is a server that allows tests to use web browser instances running on remote machines.With selenium Grid one server acts as the hub.Tests contact the hub to obtain access to browser instances.
Enter fullscreen mode Exit fullscreen mode

Features of Selenium GRID are as follows:

SeleniumGrid allows running tests in parallel on multiple machines and managing different browser versions.
The ability to run the tests on remote browser instances is useful to spread th load of testing across several machines.
Run tests in browsers running on different platforms.

                   **Conclusion:-**

 Selenium is a dynamic tool for automation web browsers which offers the components like Selenium IDE,RC,WebDriver and Grid for more information of web testing.It is a support for various languages and parallel execution which makes it a powerful choice for automation.


        ## 2.Significance of Python Virtual Machine
Enter fullscreen mode Exit fullscreen mode

A python virtual environment is an isolated environment that allows you to install and manage dependencies for a python project seperately from other projects and the system-wide python installation.This isolation ensures that the dependencies and packages of one project do not interface with those of another.
A python virtual environment is simply a directory with a particular file structure.It has a 'bin' subdirectory that includes links to a python interpreter as well as subdirectories that hold packages installed in the specific 'venv'.
By invoking the python interpreter using the path to the 'venv's ' bin subdirectory, the python interpreter knows to use the associated packages within the 'venv'(as opposed to any packages installed alongside the actual location of the python interpreter).It is in this sense that 'venvs' are "virtual",they are not virtual in the sense of say a virtual machine.
When we setup a virtual environment we can immediately use it by invoking python using the full path to the 'bin' subdirectory within your 'venv'.
For convenience when you setup a venv it provides an activate script that you can invoke which will put the bin subdirectory for your venv first on your path.(It also update your shell prompt to let you know this change is in effect).When your venc is activated you no longer need to use the full path to the python interpreter.
Important :If we invoke python program with the full path to the python interpreter in the virtual environment,it will run in the virtual environment even if you are not in an interactive session where you used the 'activate' script.

Here are the detailed reasons why Python virtual environments are significant.

     **Dependency Management**:-

_Isolation of Dependencies_ - virtual environments create isolated spaces for projects ensuring that libraries and dependencies installed for one project do not affect other projects.
Enter fullscreen mode Exit fullscreen mode

Version Conflicts - Different projects might require different versions of the same package.
Virtual Environments allow you to install and use multiple versions of a package simultaneously without conflict.

          **Reproducibility**:- 
Enter fullscreen mode Exit fullscreen mode

Consistent Development Environment- By using a virtual environment yo can ensure that all developers working on a project have a consistent environment.This consistency minimize the works on my machine problem.
Requirements File - Virtual Environment often use a requirement.txt file to list all dependencies.This file can be shared with others to recreate the exact environment using

pip install -r requirment.txt

                **Security:-**
Enter fullscreen mode Exit fullscreen mode

Reduced Risk of System Contamination - Installing packages system wide can potentially interfere with system tools and other applications.Using virtual environments limits the scope of installations to the project directory,reducing the risk of breaking the system python or other applications.
Controlled Environment - You can test how your application behaves with different versions of dependencies or even with new or experimental packageswithout affecting the system-wide python environment.

          **Development And Testing:-**
Enter fullscreen mode Exit fullscreen mode

Testing Across Environments - Virtual Environmenta allow developers to test their applications in environments that mimic production settings or other specific configurations.This is crucial for debugging and ensuring compatibility.
Continuous Integration - Many CI/CD pipelines use virtual environments to create clean,isolated environments for running tests and building applications.This ensure that tests are run in a consistant state.

           **Portability:-**
Enter fullscreen mode Exit fullscreen mode

Project Portability - projects with a defined environment(requirement.txt) can be easily shared and run on different machines,ensuring the same dependencies are installed.
Ease of Setup - New developers can quickly setup their development environment by creating a virtual environment and installing dependencies as specified in the projects requirements file.

              **Flexibility:-**
Enter fullscreen mode Exit fullscreen mode

Multiple Environments - Developers can work on multiple projects simultaneously each with its own set of dependencies and configurations without interference.
Custom Configurations - Virtual environments allow for custom configurations and package versions tailored specifically to each projects needs.

        **Importance of Python Virtual Environment**

The importance of python virtual environments becomes apparent when we have various python projects on the same machine that depend on different versions of the same packages.
Enter fullscreen mode Exit fullscreen mode

For Example,imagine working on two different projects one using recent version of the package name and other using oldest version.This would lead to compatibility issues because python cannot simultaneously use multiple versions of the same package.
The other use case that magnifies the importance of using python virtual environments is when you are working on managed servers or production environments where you cant modify the system-wide packages because of specific requirements.
Python virtual environments create isolated contexts to keep dependencies required by different projects seperate so they dont interfere with other projects or system-wide packages.
Basically setting up virtual environments is the best way to isolate different python projects,especially if these projects have different and conflicting dependencies.
Imagine yourself walking into a grocery store for a specific item.However to your surprise there is absolutely no organization within the entire store,no way to distinguish between products.no way to tell what product is for what purpose,simply no way to find your item.
you go to the counter and ask the grocer where the specific product is,but all he tells you is to "search for it".
Now what do you do? The only option left for you is to find the item you so desperately want on your own by searching every product in the store.
This grocery store is your computer, your python package bin.All those disorganised products lying on the shelf are the endless torrent of packages you have installed over the years for your random projects.
The next time you start a project ,you will not understand if the version is up to date,if it collides with another packageor if the package exist at all.such organization can cause setbacks and that not only disrupts your projects but takes away the valuable moment that otherwise could have been used for something more productive.
The solution for that is python virtual environment helps decoulpe and isolate versions of python and their related pip versions.This authorizes end-users to install and manage their own set of software that is independent of those provided by the system.

          **Use of Virtual Environment:-**

     With a virtual environment you have complete control over the environment.you would know the package versions that are required to be updated and what versions are installed.virtual environment give you a replicable and stable environment.
  You have complete contol over the versions of python used,the installed packages,and their scheduled upgrades.In fact the modern versions of the python support virtual environments over the boundary.
If you need to have a say on your updates to new packages of python, all you need is to create your own python interpreter and create a virtual world based on the interpreter.By this process you can disengage the servers from the system python update schedule.
Enter fullscreen mode Exit fullscreen mode

There is however an exception to using a virtual environment.suppose you have a simple program that only uses modules from the PythonStandardLibrary.In such a case,you might contemplate not using a simulated environment.
Python has various modules and versions for different applications.A project may required a third party library which is installed.Another project uses a similar directory for retrieval and storage but doesnt require third party software.So the simulated environment can come into play and create a different scheduled environment for both the projects and each project can store and retrieve packages from their specific environments.

               **Tools and Usage:-**
Enter fullscreen mode Exit fullscreen mode

Virtualenv and venv :
Tools like 'virtualenv' python's build in 'venv'module are used to create virtual environments.'virtualenv' is a third-party tool that offers additional features,while 'venv' included in python's standard library.
Pipenv :
pipenv that another tool that combines the functionalities of 'pip' and 'virtualen'providing a comprehensive tool for managing virtual environments and dependencies.

              **Workflow-Comments:-**
Enter fullscreen mode Exit fullscreen mode

Installing Python Virtual Environment Module:
pip install virtualenv
Verifying Python Virtual Environment Module :
virtualenv --version
Creating Virtual Environment:
It will created per project and it will create a folder for your project.
virtualenv
cd
Activating the virtual Environment:
Just activate your virtual environment and start writting your python code
scripts\activate
deactivating the virtual environment:
Just deactivating virtual environment and go to the globall access.
scripts\deactivate
Installing dependencies:
pip install selenium
Freezing Requirements:
pip freeze>requirement.txt

        **Pros of Virtual Environment** :
Enter fullscreen mode Exit fullscreen mode

you can use any package of python you want for a particular environment without having to worry about collisions.
you can arrange your packages much better and know exactly which packages you need to run your code in case someone else wants to run the code on their machine.
your main python versions directly does not get flooded with unnecessary python packages.
comes in stock with pythond and no extra tools are required.
Builds a primary virtualenv that works with almost all the tools:requirement.txt suports every domain manager using command pip.

       **Cons of Virtual Environment** :
Enter fullscreen mode Exit fullscreen mode

It acknowledges the software that is installed:builds a domain with the help of everything that had invoked python to build it,so you are still in the loop of manually controlling the versions of python.
No whistles and no bells but only the installable _pip in the domain.

                       **Conclusion**:

 Python virtual environments are a fundamental tool for modern python development.They provide essential isolation,sensuring that dependencies and packages required for one project do not interfere with those of another.This isolation not only facilitates smooth development and testing but also enhances security,reproducibility and portability of projects.



        ## 3.Examples of Python Virtual Environment
Enter fullscreen mode Exit fullscreen mode

Here are some specific examples that illustrate the significance of python virtual environments showing how they can be used to solve real world development problems.

       **Example-1:Dependency Isolation**:

  Virtual environment creates isolated spaces for your projects allowing you to manage dependencies for each project independently.
Enter fullscreen mode Exit fullscreen mode

Preventing Conflicts:
Different projects often require different versions of the same packages.A virtual environment ensures that the packages used in one project do not intefere with those in another.
Scenario:
you are working on two different projects that require different versions of the same library.
Details:
Project A requires 'Selenium-3.6'.
Project B requires 'Selenium-4.0'.
Without Virtual Environment:
Installing selenium globally means you can only have one version installed at a time.
If you switch version to work on one project,the project may break.
With Virtual Environment:
Create a Virtual Environment for each project.
#create and activate virtual environment for project A
python -m venv project_a_env
source project_a_env/bin/activate
pipn install selenium ==3.6
deactivate
#create and activate virtual environment for project B
python -m venv project_b_env
source project_b_env/bin/activate
pipn install selenium ==4.0
deactivate
Each project now has its own isolated environment with the rquired version of selenium.

          **Example-2:Reproducibility**

Virtual Environments help ensure that your development environment can be replicated exactly which is crucial for consistent behavior across different systems.
Enter fullscreen mode Exit fullscreen mode

Ensuring Consistency:
By using virtual environments you can share the exact environment setup with your team.
Scenario:
you are collaborating on a project with team.To ensure everyone has the same development environment you use a 'requirements.txt'file.
Details:
Generate 'requirements.txt':
'pip freeze>requirements.txt'
Share 'requirements.txt' with your team.
Without Virtual Environment :
Team members might have different versions of packages installed globally leading to inconsistence.
Witn Virtual Environment:
Each team member can create a virtual environment and install dependencies from 'requirements.txt':
python -m venv project_env
source project_env/bin/activate
pip install -r requirements.txt
This ensures that all team members are working with the exact same set of dependencies,avoiding 'it works on my machine' issues.

            **Example-3:Safe Experimentation**

  Virtual environment allows you to experiment with new packages or different versions of packages without risking your main project environment.
Enter fullscreen mode Exit fullscreen mode

Sandbox for Testing:
you can create a temporary virtual environment to test new libraries or versions.If something goes wrong it doesn't affect your main project.
Scenario:
you want to test a new library or a different version of a library without affecting your main development environment.
Details:
Create a new Virtual Environment:
python -m venv test_env
source test_env/bin/activate
Install the new library or version:
pip install some_new_library
Test the library in isolation.
Without Virtual Environments:
Installing or upgrading packages globally might break your existing projects due to incompatible dependencies.
With Virtual Environments:
Experimentation is done safely within an isolated environment.If things go wrong your main project remains unaffected

  **Example-4:Multiple projects with different requirements**

Virtual environments make it easier to manage dependencies for multiple projects on the same machine.
Enter fullscreen mode Exit fullscreen mode

Project-specific dependencies:
Each project can have its own virtual environment with its own dependencies which avoids the complexity of managing a single global environment.
Scenario:
you have multiple projects that require different sets of libraries and versions.
Details:
Create seperate virtual environments for each project:

for project1

pythin -m venv project1_env
source project1_env/bin/activate
pip install libraryA==1.0 libraryB==2.0
deactivate

for project2

pythin -m venv project2_env
source project2_env/bin/activate
pip install libraryA==3.0 libraryC==1.0
deactivate
Without Virtual Environment:
Managing different versions of libraries becomes cumbersome and error-prone.
With Virtual Environments:
Each project has its own isolated environment with the specific libraries and versions it requires,preventing conflicts and ensuring stability.

         **Example-5:Deployment Consistency**

Virtual environments ensure that the environment on your development machine matches the environment on the production server.
Enter fullscreen mode Exit fullscreen mode

Seamless Deployment:
By deploying the same virtual environment you used for development,you avoid issues caused by discrepancies between development and production environments.
Scenario:
you need to deploy a web application to a production server and it is critical that the server has the exact same environmentas your development machine.
Details:
Create a virtual environment and install dependencies:
python -m venv deploy_env
source deploy_env/bin/activate
pip install -r requirements.txt
Package the application along with the virtual environment.
On the production server activate the environment and run the application:
source deply_env/bin/activate
python app.py
Without Virtual Environment:-
Differences in installed packages and their versions between development and production environments can cause deployment issues.
With Virtual Environment:
The production server has the same libraries and versions as the development environment,reducing deployment issues and ensuring consistency.

        **Example6:Using different Python versions**

Virtual Environment can be created with different versions of python which is useful for testing compatibility and managing legacy systems.
Enter fullscreen mode Exit fullscreen mode

Python Version Management:
you can create environmemnts with specific python versions making it easier to test your code across multiple python versions.
Scenario:
you need to test your code on different versions of python to ensure compatibility.
Details:
Install multiple python versions on your machine.
Create Virtual Environments with different python interpreters:
python 3.6 -m venv env36
python 3.7 -m venv env37
python 3.8 -m venv env38
Without Virtual Environment:
Switching python versions and managing dependencies manually can be error-prone and time consuming.
With Virtual Environments:
Each environment can use a specific python version and set of dependencies making it easy to test and ensure compatibility across different python versions.

Pycharm can be used as an example to demonstrate the significance and practical benefits of using Python virtual environments.Here is a detailed explanation of how Pycharm leverages virtual environments and why this integration is significant:

    **Pycharm and Python Virtual Environments:-**

 **Automatic Creation and Management**:

Pycharm simplifies the process of creating and managing virtual environments,which underscores the importance of virtual environments in maintaining clean and organized development setup.
Enter fullscreen mode Exit fullscreen mode

Creating Virtual Environments-
When starting a new project pycharm offers to create a new virtual environment automatically.This ensure that each project is isolated from others and has its oen dependencies.
'When u create a new project pycharm prompts:
-Select interpreter:[New virtualenv environment,conda environmentpipenv environment,etc.]
-Location:[specify path]
-Base Interpreter:[select python version]

Dependency Isolation -
Using virtual environments within Pycharm ensures that dependencies for one project do not interfere with those of another.This isolation is crucial for projects with conflicting library requirements.
Example Scenario:
Project A requires 'Django 2.2'
Project B requires 'Django 3.2'
By creating seperate virtual environment for each project within Pycharm,you can manage these dependencies without conflicts.
[project A : Virtual Environment with Django 2.2]
[project B : Virtual Environment with Django 3.2]

Reproducibility -
Pycharm helps ensure that the development environment can be reproduced accurately on different machines which is vital for team collaboration and deployment.
Requirements File Management:
Pycharm can generate 'requirements.txt' file from the installed packages in the virtual environment.This file can be shared with team members to recreate the same environmet.
-Generate requirement.txt: pip freeze>requirements.txt
-Install from requirements.txt: pip install -r requirements.txt

**Safe Experimentation**:
Enter fullscreen mode Exit fullscreen mode

Pycharm allows developers to experiment with new package or different versions of existing packages in an isolated environment without affecting the main project.
Example Scenario:
you want to test a new version of a library.
create a new virtual environment in Pycharm and install the new library version there.
If the experiment fails,the main project remains unaffected.
-create a test environment: python -m venv test_venv
-Activate and test new packages: pip install new_library

 **Multiple Python Versions**:
Enter fullscreen mode Exit fullscreen mode

Pycharm supports managing projects with different Python versions which is essential for maintaining legacy codebases while adopting new python features.
Example Scenarion:
Project A requires Python-3.6
Project B requires Python-3.8
By creating seperate virtual environments with different python interpreters,Pycharm helps manage these requirements seamlessly.
-Project A: Virtual Environment with Python-3.6
-Project B: Virtual Environment with python-3.8

        **Practical Steps in Pycharm**
Enter fullscreen mode Exit fullscreen mode

Creating a Virtual Environment for a New Project:

Open Pycharm and Create a New Project:
Select "create new project".
Choose the project location.
Select "new environment using" and choose 'virtualenv','conda'or 'pipenv'.
Specify the base interpreter(e.g-python 3.8).
Configuring an Existing Project:
Open the existing project in pycharm.
Go to file>setting.
Navigate to 'project:python interpreter'.
Clicking the gear icon and selct 'Add'.
Choose 'Virtualenv Environment' and specify the location or create a new one.

       **Managing Dependencies**
Enter fullscreen mode Exit fullscreen mode

Installing Packages:
Open the terminal inpycharm.
Ensure the virtual environment is active.
Install packages using 'pip install'.
Generating and using 'requirements.txt':
Generate the file :
'pip freeze>requirements.txt'
Install dependencies from the file:
'pip install -r requirements.txt'

                **  Conclusion:**
Enter fullscreen mode Exit fullscreen mode

Using Pycharm as an example highlights the significance of python virtual environments in several key areas like dependency isolation,reproducibility,safe experimentation and managing multiple python versions.Pycharm's integrated tool make it easy to create,manage and utilize virtual environments showcasing the practical benefits and necessity of virtual environments in python development.

Top comments (0)