Skip to content

Commit f840088

Browse files
Merge pull request #1 from BrowserStackCE/develop
Pytest Appium Integration
2 parents 2c917fd + 36a604b commit f840088

21 files changed

Lines changed: 757 additions & 0 deletions

File tree

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.vscode
2+
__pycache__
3+
.pytest_cache
4+
local.log
5+
testSele

README.md

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
# PyTest with Browserstack AppAutomate
2+
3+
PyTest Integration with BrowserStack.
4+
5+
![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780)
6+
### Requirements
7+
8+
1. Python 3.6+ or Python 2.7+
9+
10+
- For Windows, download latest python version from [here](https://www.python.org/downloads/windows/) and run the installer executable
11+
- For Mac and Linux, run `python --version` to see what python version is pre-installed. If you want a different version download from [here](https://www.python.org/downloads/)
12+
13+
### Install the dependencies
14+
15+
To install the dependencies, run the following command in project's base directory:
16+
17+
- For Python 3
18+
19+
```sh
20+
pip3 install -r requirements.txt
21+
```
22+
23+
- For Python 2
24+
25+
```sh
26+
pip install -r requirements.txt
27+
```
28+
29+
## Getting Started
30+
31+
Getting Started with Pytest-Appium tests in Python on BrowserStack couldn't be easier!
32+
33+
### Run your first test :
34+
35+
**1. Upload your Android or iOS App**
36+
37+
Upload your Android app (.apk or .aab file) or iOS app (.ipa file) to BrowserStack servers using our REST API. Here is an example cURL request :
38+
39+
```
40+
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \
41+
-X POST "https://api-cloud.browserstack.com/app-automate/upload" \
42+
-F "file=@/path/to/apk/file"
43+
```
44+
45+
Ensure that @ symbol is prepended to the file path in the above request. Please note the `app_url` value returned in the API response. We will use this to set the application under test while configuring the test later on.
46+
47+
**Note**: If you do not have an .apk or .ipa file and are looking to simply try App Automate, you can download and test using our [sample Android app](https://www.browserstack.com/app-automate/sample-apps/android/WikipediaSample.apk) or [sample iOS app](https://www.browserstack.com/app-automate/sample-apps/ios/BStackSampleApp.ipa).
48+
49+
50+
**2. Configure and run your first single test**
51+
52+
Open `single.json` file in `android/run-single-test` folder for Android and `ios/run-single-test` folder for iOS:
53+
54+
- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)
55+
56+
- Replace `bs://<app-id>` with the URL obtained from app upload step
57+
58+
- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)
59+
60+
- Run the below command to execute a single Android test on BrowserStack AppAutomate:
61+
```
62+
cd android
63+
paver run single
64+
```
65+
66+
- Run the below command to execute a single iOS test on BrowserStack AppAutomate:
67+
```
68+
cd ios
69+
paver run single
70+
```
71+
72+
**3. Configure and run your parallel test**
73+
74+
- In order to run tests in parallel across different configurations, Open `parallel.json` file in `android/run-parallel-test` folder for Android and `ios/run-parallel-test` folder for iOS
75+
76+
- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)
77+
78+
- Replace `bs://<app-id>` wkth the URL obtained from app upload step
79+
80+
- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)
81+
82+
- Run the below command to execute parallel Android test on BrowserStack AppAutomate:
83+
```
84+
cd android
85+
paver run parallel
86+
```
87+
88+
- Run the below command to execute a parallel iOS test on BrowserStack AppAutomate:
89+
```
90+
cd ios
91+
paver run parallel
92+
```
93+
94+
- You can access the test execution results, and debugging information such as video recording, network logs on [App Automate dashboard](https://app-automate.browserstack.com/dashboard)
95+
96+
---
97+
98+
### **Use Local testing for apps that access resources hosted in development or testing environments :**
99+
100+
**1. Upload your Android or iOS App**
101+
102+
Upload your Android app (.apk or .aab file) or iOS app (.ipa file) that access resources hosted on your internal or test environments to BrowserStack servers using our REST API. Here is an example cURL request :
103+
104+
```
105+
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \
106+
-X POST "https://api-cloud.browserstack.com/app-automate/upload" \
107+
-F "file=@/path/to/apk/file"
108+
```
109+
110+
Ensure that @ symbol is prepended to the file path in the above request. Please note the `app_url` value returned in the API response. We will use this to set the application under test while configuring the test later on.
111+
112+
**Note**: If you do not have an .apk or .ipa file and are looking to simply try App Automate, you can download and test using our [sample Android Local app](https://www.browserstack.com/app-automate/sample-apps/android/LocalSample.apk) or [sample iOS Local app](https://www.browserstack.com/app-automate/sample-apps/ios/LocalSample.ipa).
113+
114+
115+
**2. Configure and run your local test**
116+
117+
Open `local.json` file in `android/run-local-test` folder for Android and `ios/run-local-test` folder for iOS:
118+
119+
120+
- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)
121+
122+
- Replace `bs://<app-id>` wkth the URL obtained from app upload step
123+
124+
- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)
125+
126+
- Ensure that `local` capability is set to `true`. The `conftest.py` contains the code snippet that automatically establishes Local Testing connection to BrowserStack servers using Python binding for BrowserStack Local.
127+
128+
- Run the below command for Android:
129+
```
130+
cd android
131+
paver run local
132+
```
133+
134+
- Run the below command for iOS:
135+
```
136+
cd ios
137+
paver run local
138+
```
139+
140+
- You can access the test execution results, and debugging information such as video recording, network logs on [App Automate dashboard](https://app-automate.browserstack.com/dashboard)

android/conftest.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import pytest
2+
from browserstack.local import Local
3+
import os
4+
from appium import webdriver
5+
import json
6+
from jsonmerge import merge
7+
CONFIG_FILE = os.environ['CONFIG_FILE'] if 'CONFIG_FILE' in os.environ else 'run-single-test/single.json'
8+
TASK_ID = int(os.environ['TASK_ID']) if 'TASK_ID' in os.environ else 0
9+
10+
with open(CONFIG_FILE) as data_file:
11+
CONFIG = json.load(data_file)
12+
13+
bs_local = None
14+
15+
BROWSERSTACK_USERNAME = os.environ['BROWSERSTACK_USERNAME'] if 'BROWSERSTACK_USERNAME' in os.environ else CONFIG["user"]
16+
BROWSERSTACK_ACCESS_KEY = os.environ['BROWSERSTACK_ACCESS_KEY'] if 'BROWSERSTACK_ACCESS_KEY' in os.environ else CONFIG["key"]
17+
18+
19+
def start_local():
20+
"""Code to start browserstack local before start of test."""
21+
global bs_local
22+
bs_local = Local()
23+
bs_local_args = {
24+
"key": BROWSERSTACK_ACCESS_KEY or "access_key", "forcelocal": "true"}
25+
bs_local.start(**bs_local_args)
26+
27+
28+
def stop_local():
29+
"""Code to stop browserstack local after end of test."""
30+
global bs_local
31+
if bs_local is not None:
32+
bs_local.stop()
33+
34+
35+
@pytest.fixture(scope='session')
36+
def session_capabilities():
37+
capabilities = merge(CONFIG['environments']
38+
[TASK_ID], CONFIG["capabilities"])
39+
capabilities['bstack:options']['userName'] = BROWSERSTACK_USERNAME
40+
capabilities['bstack:options']['accessKey'] = BROWSERSTACK_ACCESS_KEY
41+
if "local" in capabilities['bstack:options'] and capabilities['bstack:options']['local']:
42+
start_local()
43+
return capabilities
44+
45+
46+
@pytest.fixture(scope='function')
47+
def setWebdriver(request, session_capabilities):
48+
remoteURL = "https://hub.browserstack.com/wd/hub"
49+
driver = webdriver.Remote(remoteURL, session_capabilities)
50+
request.cls.driver = driver
51+
52+
yield driver
53+
54+
driver.quit()
55+
56+
57+
def pytest_sessionfinish(session, exitstatus):
58+
stop_local()

android/pavement.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from paver.easy import *
2+
from paver.setuputils import setup
3+
from multiprocess import Process
4+
import platform
5+
import json
6+
7+
def run_py_test(config, task_id=0):
8+
if platform.system() == "Windows":
9+
if(config=="local"):
10+
sh('cmd /C "set CONFIG_FILE=run-local-test/%s.json && set TASK_ID=%s && pytest -s run-local-test/tests/*.py"' % (config, task_id))
11+
elif(config == "parallel"):
12+
sh('cmd /C "set CONFIG_FILE=run-parallel-test/%s.json && set TASK_ID=%s && pytest -s run-parallel-test/tests/*.py -n 2"' % (config, task_id))
13+
else:
14+
sh('cmd /C "set CONFIG_FILE=run-single-test/%s.json && set TASK_ID=%s && pytest -s run-single-test/tests/*.py"' % (config, task_id))
15+
16+
else:
17+
if(config=="local"):
18+
sh('CONFIG_FILE=run-local-test/%s.json TASK_ID=%s pytest -s run-local-test/tests/*.py' % (config, task_id))
19+
elif(config == "parallel"):
20+
sh('CONFIG_FILE=run-parallel-test/%s.json TASK_ID=%s pytest -s run-parallel-test/tests/*.py -n 2' % (config, task_id))
21+
else:
22+
sh('CONFIG_FILE=run-single-test/%s.json TASK_ID=%s pytest -s run-single-test/tests/*.py' % (config, task_id))
23+
24+
@task
25+
@consume_nargs(1)
26+
def run(args):
27+
"""Run single, local and parallel test using different config."""
28+
jobs = []
29+
config_file = 'run-%s-test/%s.json' % (args[0], args[0])
30+
with open(config_file) as data_file:
31+
CONFIG = json.load(data_file)
32+
environments = CONFIG['environments']
33+
for i in range(len(environments)):
34+
p = Process(target=run_py_test, args=(args[0], i))
35+
jobs.append(p)
36+
p.start()

android/run-local-test/local.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"user": "BROWSERSTACK_USERNAME",
3+
"key": "BROWSERSTACK_ACCESS_KEY",
4+
"capabilities": {
5+
"app" : "bs://<app-id>",
6+
"bstack:options": {
7+
"projectName": "Pytest Android Project",
8+
"buildName": "browserstack-build-1",
9+
"sessionName": "BStack local_test",
10+
"local": "true",
11+
"debug": "true",
12+
"networkLogs": "true"
13+
}
14+
},
15+
"environments": [
16+
{
17+
"platformName": "android",
18+
"platformVersion": "9.0",
19+
"deviceName": "Google Pixel 3"
20+
}
21+
]
22+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from browserstack.local import Local
2+
from appium import webdriver
3+
from appium.webdriver.common.appiumby import AppiumBy
4+
from selenium.webdriver.support.ui import WebDriverWait
5+
from selenium.webdriver.support import expected_conditions as EC
6+
import time
7+
import pytest
8+
from selenium.webdriver.common.by import By
9+
10+
11+
@pytest.mark.usefixtures('setWebdriver')
12+
class TestSample:
13+
14+
def test_example(self):
15+
test_button = WebDriverWait(self.driver, 30).until(
16+
EC.element_to_be_clickable(
17+
(AppiumBy.ID, "com.example.android.basicnetworking:id/test_action"))
18+
)
19+
20+
test_button.click()
21+
22+
time.sleep(5)
23+
24+
test_element = None
25+
search_results = self.driver.find_elements(AppiumBy.CLASS_NAME, "android.widget.TextView")
26+
print(len(search_results))
27+
for result in search_results:
28+
if "Up and running" in result.text:
29+
test_element = result
30+
31+
if test_element is None:
32+
self.driver.execute_script(
33+
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Cannot find the needed TextView element from app"}}')
34+
else:
35+
self.driver.execute_script(
36+
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Test Passed Successfully"}}')
37+
38+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"user": "BROWSERSTACK_USERNAME",
3+
"key": "BROWSERSTACK_ACCESS_KEY",
4+
"capabilities": {
5+
"app" : "bs://<app-id>",
6+
"bstack:options": {
7+
"projectName": "Pytest Android Project",
8+
"buildName": "browserstack-build-1",
9+
"sessionName": "BStack parallel_test",
10+
"local": false,
11+
"debug": "true",
12+
"networkLogs": "true"
13+
}
14+
},
15+
"environments": [
16+
{
17+
"platformName": "android",
18+
"platformVersion": "9.0",
19+
"deviceName": "Google Pixel 3"
20+
},
21+
{
22+
"platformName": "android",
23+
"platformVersion": "11.0",
24+
"deviceName": "Samsung Galaxy A52"
25+
}
26+
]
27+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from browserstack.local import Local
2+
from appium import webdriver
3+
from appium.webdriver.common.appiumby import AppiumBy
4+
from selenium.webdriver.support.ui import WebDriverWait
5+
from selenium.webdriver.support import expected_conditions as EC
6+
import time
7+
import pytest
8+
from selenium.webdriver.common.by import By
9+
10+
@pytest.mark.usefixtures('setWebdriver')
11+
class TestSample:
12+
13+
def test_example(self):
14+
search_element = WebDriverWait(self.driver, 30).until(
15+
EC.element_to_be_clickable(
16+
(AppiumBy.ACCESSIBILITY_ID, "Search Wikipedia"))
17+
)
18+
19+
search_element.click()
20+
search_input = WebDriverWait(self.driver, 30).until(
21+
EC.element_to_be_clickable(
22+
(AppiumBy.ID, "org.wikipedia.alpha:id/search_src_text"))
23+
)
24+
search_input.send_keys("BrowserStack")
25+
time.sleep(5)
26+
search_results = self.driver.find_elements(
27+
AppiumBy.CLASS_NAME, "android.widget.TextView")
28+
29+
if(len(search_results) > 0):
30+
self.driver.execute_script(
31+
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Test Passed Successfully"}}')
32+
else:
33+
self.driver.execute_script(
34+
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Test Failed"}}')

0 commit comments

Comments
 (0)