├── .gitignore
├── .gitpod.yml
├── README.md
├── configurations.json
├── conftest.py
├── requirements.txt
├── smartui_sample.py
└── tests
└── lt_sample_todo.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | venv
3 | .idea/
4 | __pycache__
5 | .pytest_cache
--------------------------------------------------------------------------------
/.gitpod.yml:
--------------------------------------------------------------------------------
1 | # This configuration file was automatically generated by Gitpod.
2 | # Please adjust to your needs (see https://www.gitpod.io/docs/config-gitpod-file)
3 | # and commit this file to your remote git repository to share the goodness with others.
4 |
5 | tasks:
6 | - init: pip install -r requirements.txt && pytest --workers 2 -s tests/lt_sample_todo.py
7 |
8 |
9 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Run Selenium Tests With pytest On LambdaTest
2 |
3 | 
4 |
5 |
6 | Blog
7 | ⋅
8 | Docs
9 | ⋅
10 | Learning Hub
11 | ⋅
12 | Newsletter
13 | ⋅
14 | Certifications
15 | ⋅
16 | YouTube
17 |
18 |
19 |
20 |
21 |
22 | *Learn how to run your Python automation testing scripts using pytest on the LambdaTest platform*
23 |
24 | [
](https://accounts.lambdatest.com/register)
25 |
26 |
27 | ## Table Of Contents
28 |
29 | * [Pre-requisites](#pre-requisites)
30 | * [Run Your First Test](#run-your-first-test)
31 | * [Local Testing With pytest](#testing-locally-hosted-or-privately-hosted-projects)
32 | ## Prerequisites
33 |
34 | Before you can start performing **Python 3** automation testing using **pytest**, you would need to:
35 |
36 | * Install the latest Python build from the [official website](https://www.python.org/downloads/). We recommend using the latest version.
37 | * Make sure **pip** is installed in your system. You can install **pip** from [here](https://pip.pypa.io/en/stable/installation/).
38 | * Download the latest **Selenium Client** and its **WebDriver bindings** from the [official website](https://www.selenium.dev/downloads/). Latest versions of **Selenium Client** and **WebDriver** are ideal for running your automation script on LambdaTest Selenium cloud grid.
39 | * Install **virtualenv** which is the recommended way to run your tests. It will isolate the build from other setups you may have running and ensure that the tests run with the specified versions of the modules.
40 |
41 | ```bash
42 | pip install virtualenv
43 | ```
44 | ### Installing Selenium Dependencies And Tutorial Repo
45 |
46 | **Step 1:** Clone the LambdaTest’s pytest-selenium-sample repository and navigate to the code directory as shown below:
47 | ```bash
48 | git clone https://github.com/LambdaTest/pytest-selenium-sample
49 | cd pytest-selenium-sample
50 | ```
51 | **Step 2:** Create a virtual environment in your project folder the environment name is arbitrary.
52 | ```bash
53 | virtualenv venv
54 | ```
55 | **Step 3:** Activate the environment.
56 | ```bash
57 | source venv/bin/activate
58 | ```
59 | **Step 4:** Install the [required packages](https://github.com/LambdaTest/pytest-selenium-sample/blob/master/requirements.txt) from the cloned project directory:
60 | ```bash
61 | pip install -r requirements.txt
62 | ```
63 |
64 | ### Setting Up Your Authentication
65 |
66 | Make sure you have your LambdaTest credentials with you to run test automation scripts. You can get these credentials from the [LambdaTest Automation Dashboard](https://automation.lambdatest.com/build/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample) or by your [LambdaTest Profile](https://accounts.lambdatest.com/login/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample).
67 |
68 | **Step 5:** Set LambdaTest **Username** and **Access Key** in environment variables.
69 |
70 | * For **Linux/macOS**:
71 |
72 | ```bash
73 | export LT_USERNAME="YOUR_USERNAME"
74 | export LT_ACCESS_KEY="YOUR ACCESS KEY"
75 | ```
76 | * For **Windows**:
77 | ```bash
78 | set LT_USERNAME="YOUR_USERNAME"
79 | set LT_ACCESS_KEY="YOUR ACCESS KEY"
80 | ```
81 |
82 | ## Run Your First Test
83 |
84 | >**Test Scenario**: The [lt_sample_todo.py](https://github.com/LambdaTest/pytest-selenium-sample/blob/master/tests/lt_sample_todo.py) sample script tests a simple to-do application with basic functionalities like mark items as done, add items in a list, calculate total pending items etc.
85 |
86 | ### Configuration Of Your Test Capabilities
87 |
88 | **Step 6:** In the python script, you need to update your test capabilities. In this code, we are passing browser, browser version, and operating system information, along with LambdaTest Selenium grid capabilities via capabilities object.
89 |
90 | The capabilities object in the above code are defined as:
91 |
92 | ```python
93 | capabilities = {
94 | "build": "your build name",
95 | "name": "your test name",
96 | "platformName": "Windows 10"
97 | "browserName": "Chrome",
98 | "browserVersion": "latest",
99 | }
100 | ```
101 | You can generate capabilities for your test requirements with the help of our inbuilt [Desired Capability Generator](https://www.lambdatest.com/capabilities-generator/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample).
102 |
103 |
104 | ### Executing The Test
105 |
106 | **Step 7:** You would need to execute the below command in your terminal/cmd.
107 |
108 | ```bash
109 | pytest -s tests/lt_sample_todo.py
110 | ```
111 | Your test results would be displayed on the test console (or command-line interface if you are using terminal/cmd) and on LambdaTest automation dashboard. [LambdaTest Automation Dashboard](https://automation.lambdatest.com/build/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample) will help you view all your text logs, screenshots and video recording for your entire automation tests.
112 |
113 | ## Run Your Parallel Tests Using PyTest Framework
114 |
115 | To run parallel tests using PyTest, we would have to execute the below command in the terminal:
116 |
117 | ```bash
118 | pytest --workers 2 -s tests/lt_sample_todo.py
119 | ```
120 |
121 | ## Testing Locally Hosted Or Privately Hosted Projects
122 |
123 | You can test your locally hosted or privately hosted projects with LambdaTest Selenium grid using LambdaTest Tunnel. All you would have to do is set up an SSH tunnel using tunnel and pass toggle `tunnel = True` via desired capabilities. LambdaTest Tunnel establishes a secure SSH protocol based tunnel that allows you in testing your locally hosted or privately hosted pages, even before they are live.
124 |
125 | Refer our [LambdaTest Tunnel documentation](https://www.lambdatest.com/support/docs/testing-locally-hosted-pages/) for more information.
126 |
127 | Here’s how you can establish LambdaTest Tunnel.
128 |
129 | Download the binary file of:
130 | * [LambdaTest Tunnel for Windows](https://downloads.lambdatest.com/tunnel/v3/windows/64bit/LT_Windows.zip)
131 | * [LambdaTest Tunnel for macOS](https://downloads.lambdatest.com/tunnel/v3/mac/64bit/LT_Mac.zip)
132 | * [LambdaTest Tunnel for Linux](https://downloads.lambdatest.com/tunnel/v3/linux/64bit/LT_Linux.zip)
133 |
134 | Open command prompt and navigate to the binary folder.
135 |
136 | Run the following command:
137 |
138 | ```bash
139 | LT -user {user’s login email} -key {user’s access key}
140 | ```
141 | So if your user name is lambdatest@example.com and key is 123456, the command would be:
142 |
143 | ```bash
144 | LT -user lambdatest@example.com -key 123456
145 | ```
146 | Once you are able to connect **LambdaTest Tunnel** successfully, you would just have to pass on tunnel capabilities in the code shown below :
147 |
148 | **Tunnel Capability**
149 |
150 | ```
151 | "tunnel" = true
152 | ```
153 |
154 | ## Tutorials 📙
155 |
156 | Check out our latest tutorials on pytest automation testing 👇
157 |
158 |
159 | * [Basics Of The pytest Framework](https://www.lambdatest.com/blog/selenium-python-pytest-testing-tutorial/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
160 | * [Setting Up pytest: Installation And Getting Started](https://www.lambdatest.com/blog/test-automation-using-pytest-and-selenium-webdriver/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
161 | * [Pytest testing Using Selenium WebDriver](https://www.lambdatest.com/blog/selenium-webdriver-with-python/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
162 | * [Parallel Testing With pytest Selenium](https://www.lambdatest.com/blog/pytest-tutorial-parallel-testing-with-selenium-grid/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
163 | * [Parameterization In Selenium pytest](https://www.lambdatest.com/blog/parameterization-in-pytest-with-selenium/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
164 | * [Automated Browser Testing With Selenium pytest Fixtures](https://www.lambdatest.com/blog/end-to-end-tutorial-for-pytest-fixtures-with-examples/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
165 | * [Executing Multiple Test Cases From Single File](https://www.lambdatest.com/blog/pytest-tutorial-executing-multiple-test-cases-from-single-file/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
166 | * [How To Stop Test Suites After ‘N’ Test Failures](https://www.lambdatest.com/blog/how-to-stop-test-suite-after-n-test-failures-in-pytest/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
167 | * [Generating Test Reports In Selenium pytest](https://www.lambdatest.com/blog/pytest-report-generation-for-selenium-automation-scripts/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
168 |
169 |
170 | Please refer to our [PyTest Tutorial | Selenium With Python | Learn PyTest In 90 minutes | LambdaTest](https://www.youtube.com/watch?v=UzkuOACmBpA). ▶️
171 |
172 | Subscribe To Our [LambdaTest YouTube Channel 🔔](https://www.youtube.com/c/LambdaTest) and keep up-to-date on the latest video tutorial around software testing world.
173 |
174 | ## Documentation & Resources :books:
175 |
176 |
177 | Visit the following links to learn more about LambdaTest's features, setup and tutorials around test automation, mobile app testing, responsive testing, and manual testing.
178 |
179 | * [LambdaTest Documentation](https://www.lambdatest.com/support/docs/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
180 | * [LambdaTest Blog](https://www.lambdatest.com/blog/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
181 | * [LambdaTest Learning Hub](https://www.lambdatest.com/learning-hub/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
182 |
183 | ## LambdaTest Community :busts_in_silhouette:
184 |
185 | The [LambdaTest Community](https://community.lambdatest.com/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample) allows people to interact with tech enthusiasts. Connect, ask questions, and learn from tech-savvy people. Discuss best practises in web development, testing, and DevOps with professionals from across the globe 🌎
186 |
187 | ## What's New At LambdaTest ❓
188 |
189 | To stay updated with the latest features and product add-ons, visit [Changelog](https://changelog.lambdatest.com/)
190 |
191 | ## About LambdaTest
192 |
193 | [LambdaTest](https://www.lambdatest.com/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample) is a leading test execution and orchestration platform that is fast, reliable, scalable, and secure. It allows users to run both manual and automated testing of web and mobile apps across 3000+ different browsers, operating systems, and real device combinations. Using LambdaTest, businesses can ensure quicker developer feedback and hence achieve faster go to market. Over 500 enterprises and 1 Million + users across 130+ countries rely on LambdaTest for their testing needs.
194 |
195 | ### Features
196 |
197 | * Run Selenium, Cypress, Puppeteer, Playwright, and Appium automation tests across 3000+ real desktop and mobile environments.
198 | * Real-time cross browser testing on 3000+ environments.
199 | * Test on Real device cloud
200 | * Blazing fast test automation with HyperExecute
201 | * Accelerate testing, shorten job times and get faster feedback on code changes with Test At Scale.
202 | * Smart Visual Regression Testing on cloud
203 | * 120+ third-party integrations with your favorite tool for CI/CD, Project Management, Codeless Automation, and more.
204 | * Automated Screenshot testing across multiple browsers in a single click.
205 | * Local testing of web and mobile apps.
206 | * Online Accessibility Testing across 3000+ desktop and mobile browsers, browser versions, and operating systems.
207 | * Geolocation testing of web and mobile apps across 53+ countries.
208 | * LT Browser - for responsive testing across 50+ pre-installed mobile, tablets, desktop, and laptop viewports
209 |
210 |
211 | [
](https://accounts.lambdatest.com/register)
212 |
213 |
214 |
215 | ## We are here to help you :headphones:
216 |
217 | * Got a query? we are available 24x7 to help. [Contact Us](support@lambdatest.com/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
218 | * For more info, visit - [LambdaTest](https://www.lambdatest.com/?utm_source=github&utm_medium=repo&utm_campaign=pytest-selenium-sample)
219 |
220 |
--------------------------------------------------------------------------------
/configurations.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "platform": "Windows 11",
4 | "browserName": "chrome",
5 | "version": "latest"
6 | },
7 | {
8 | "platform": "Windows 10",
9 | "browserName": "firefox",
10 | "version": "latest-1"
11 | },
12 | {
13 | "platform": "Windows 8",
14 | "browserName": "edge",
15 | "version": "latest-2"
16 | }
17 | ]
--------------------------------------------------------------------------------
/conftest.py:
--------------------------------------------------------------------------------
1 | from os import environ
2 |
3 | import pytest
4 | from selenium import webdriver
5 |
6 |
7 | @pytest.fixture(scope='function')
8 | def driver(request):
9 | # parallize_test_accross_combinations
10 | desired_caps = {}
11 | browser = request.param
12 |
13 | desired_caps.update(browser)
14 | test_name = request.param["platform"] + "_" + request.param["browserName"] + "_" + request.param["version"]
15 | build = environ.get('BUILD', "Sample PY Build Chrome")
16 |
17 | tunnel_id = environ.get('TUNNEL', False)
18 | username = environ.get('LT_USERNAME', None)
19 | access_key = environ.get('LT_ACCESS_KEY', None)
20 |
21 | selenium_endpoint = "http://{}:{}@hub.lambdatest.com/wd/hub".format(username, access_key)
22 | chrome_options = webdriver.ChromeOptions()
23 | option = {
24 | "platform": "Windows 10",
25 | "version": "latest",
26 | "name": test_name,
27 | "Build": build,
28 | "video": True,
29 | "visual": True,
30 | "network": True,
31 | "console": True
32 | }
33 | chrome_options.set_capability("LT:Options", option)
34 | browser = webdriver.Remote(
35 | command_executor=selenium_endpoint,
36 | options=chrome_options
37 | )
38 | yield browser
39 |
40 | def fin():
41 | # browser.execute_script("lambda-status=".format(str(not request.node.rep_call.failed if "passed" else
42 | # "failed").lower()))
43 | if request.node.rep_call.failed:
44 | browser.execute_script("lambda-status=failed")
45 | browser.quit()
46 | else:
47 | browser.execute_script("lambda-status=passed")
48 | browser.quit()
49 |
50 | request.addfinalizer(fin)
51 |
52 |
53 | @pytest.hookimpl(tryfirst=True, hookwrapper=True)
54 | def pytest_runtest_makereport(item, call):
55 | # this sets the result as a test attribute for LambdaTest reporting.
56 | # execute all other hooks to obtain the report object
57 | outcome = yield
58 | rep = outcome.get_result()
59 |
60 | # set a report attribute for each phase of a call, which can
61 | # be "setup", "call", "teardown"
62 | setattr(item, "rep_" + rep.when, rep)
63 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | selenium>=3.14
2 | pytest==7.1.3
3 | pytest-selenium
4 | pytest-parallel
5 |
--------------------------------------------------------------------------------
/smartui_sample.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pytest
3 | from selenium import webdriver
4 | from os import environ
5 | @pytest.fixture(scope='function')
6 | def driver(request):
7 | test_name = request.node.name
8 | build = os.environ.get('BUILD', "Sample PYTEST Build")
9 | tunnel_id = os.environ.get('TUNNEL', False)
10 | username = environ.get('LT_USERNAME', None)
11 | access_key = environ.get('LT_ACCESS_KEY', None)
12 |
13 | selenium_endpoint = f"http://{username}:{access_key}@hub.lambdatest.com/wd/hub"
14 | chrome_options = webdriver.ChromeOptions()
15 | option = {
16 | "platform": "Windows 10",
17 | "version": "latest",
18 | "name": test_name,
19 | "build": build,
20 | "video": True,
21 | "visual": True,
22 | "network": True,
23 | "console": True,
24 | "smartUI.project": "Pytest-Sample",
25 | "selenium_version": "4.0.0"
26 | }
27 | chrome_options.set_capability("LT:Options", option)
28 | browser = webdriver.Remote(
29 | command_executor=selenium_endpoint,
30 | options=chrome_options
31 | )
32 | yield browser
33 | browser.quit()
34 |
35 | def test_demo_site(driver):
36 | try:
37 | driver.implicitly_wait(10)
38 | driver.set_page_load_timeout(30)
39 | print('Loading URL')
40 | driver.get("https://www.amazon.com/")
41 | driver.execute_script('smartui.takeScreenshot="Viewport Screenshot"')
42 | print("1st screenshot")
43 | driver.implicitly_wait(10)
44 | driver.execute_script('smartui.takeFullPageScreenshot="FullPage Screenshot"')
45 | print("2nd screenshot")
46 | except Exception as e:
47 | pytest.fail(f"Test failed: {str(e) if str(e) else 'Unknown error'}")
48 |
--------------------------------------------------------------------------------
/tests/lt_sample_todo.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 | import pathlib
4 | import time
5 |
6 | import pytest
7 | from selenium.webdriver.common.by import By
8 | import sys
9 | from selenium.webdriver.common.action_chains import ActionChains
10 |
11 |
12 |
13 | class TestLinkChrome:
14 | def load_params_from_json(json_path):
15 | with open(json_path) as f:
16 | return json.load(f)
17 |
18 | @pytest.mark.parametrize("driver", load_params_from_json(str(pathlib.Path(__file__).parent.parent) + "/configurations.json"), indirect=True)
19 | def test_title(self, driver):
20 |
21 | driver.get(r'https://www.lambdatest.com/selenium-playground/')
22 | driver.implicitly_wait(10)
23 | driver.find_element(By.XPATH, "//a[contains(text(),'Simple Form Demo')]").click()
24 | title = driver.current_url
25 | assert "simple-form-demo" in title, "tetx is not present n the URL"
26 | val = "Welcome to LambdaTest"
27 | driver.find_element( By.ID, "user-message").send_keys(val)
28 | # driver.find_element(By.XPATH, "//input[@id='user-message']").send_keys(val)
29 | driver.find_element(By.ID, "showInput").click()
30 | text = driver.find_element(By.CSS_SELECTOR, '#message').text
31 | assert text == val
32 |
33 |
34 | @pytest.mark.parametrize("driver", load_params_from_json(str(pathlib.Path(__file__).parent.parent) + "/configurations.json"), indirect=True)
35 | def test_item(self, driver):
36 | """
37 | Verify item submission
38 | :return: None
39 | """
40 |
41 | driver.get('https://www.lambdatest.com/selenium-playground/')
42 | driver.find_element(By.XPATH,"//a[contains(text(),'Drag & Drop Sliders')]").click()
43 | time.sleep(2)
44 | ActionChains(driver).move_by_offset(946, 349).pause(2).click().perform()
45 | exp_val= '95'
46 | obtained_val = driver.find_element(By.ID,"rangeSuccess").text
47 | assert exp_val, obtained_val=="Value is not equal to 95"
48 |
49 |
--------------------------------------------------------------------------------