Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.vscode
__pycache__
.pytest_cache
local.log
testSele
140 changes: 140 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# PyTest with Browserstack AppAutomate

PyTest Integration with BrowserStack.

![BrowserStack Logo](https://d98b8t1nnulk5.cloudfront.net/production/images/layout/logo-header.png?1469004780)
### Requirements

1. Python 3.6+ or Python 2.7+

- For Windows, download latest python version from [here](https://www.python.org/downloads/windows/) and run the installer executable
- 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/)

### Install the dependencies

To install the dependencies, run the following command in project's base directory:

- For Python 3

```sh
pip3 install -r requirements.txt
```

- For Python 2

```sh
pip install -r requirements.txt
```

## Getting Started

Getting Started with Pytest-Appium tests in Python on BrowserStack couldn't be easier!

### Run your first test :

**1. Upload your Android or iOS App**

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 :

```
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \
-X POST "https://api-cloud.browserstack.com/app-automate/upload" \
-F "file=@/path/to/apk/file"
```

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.

**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).


**2. Configure and run your first single test**

Open `single.json` file in `android/run-single-test` folder for Android and `ios/run-single-test` folder for iOS:

- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)

- Replace `bs://<app-id>` with the URL obtained from app upload step

- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)

- Run the below command to execute a single Android test on BrowserStack AppAutomate:
```
cd android
paver run single
```

- Run the below command to execute a single iOS test on BrowserStack AppAutomate:
```
cd ios
paver run single
```

**3. Configure and run your parallel test**

- 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

- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)

- Replace `bs://<app-id>` wkth the URL obtained from app upload step

- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)

- Run the below command to execute parallel Android test on BrowserStack AppAutomate:
```
cd android
paver run parallel
```

- Run the below command to execute a parallel iOS test on BrowserStack AppAutomate:
```
cd ios
paver run parallel
```

- 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)

---

### **Use Local testing for apps that access resources hosted in development or testing environments :**

**1. Upload your Android or iOS App**

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 :

```
curl -u "YOUR_USERNAME:YOUR_ACCESS_KEY" \
-X POST "https://api-cloud.browserstack.com/app-automate/upload" \
-F "file=@/path/to/apk/file"
```

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.

**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).


**2. Configure and run your local test**

Open `local.json` file in `android/run-local-test` folder for Android and `ios/run-local-test` folder for iOS:


- Replace `BROWSERSTACK_USERNAME` & `BROWSERSTACK_ACCESS_KEY` with your BrowserStack access credentials. Get your BrowserStack access credentials from [here](https://www.browserstack.com/accounts/settings)

- Replace `bs://<app-id>` wkth the URL obtained from app upload step

- Set the deviceName and platformVersion. You can refer our [Capability Generator](https://www.browserstack.com/app-automate/capabilities)

- 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.

- Run the below command for Android:
```
cd android
paver run local
```

- Run the below command for iOS:
```
cd ios
paver run local
```

- 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)
58 changes: 58 additions & 0 deletions android/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import pytest
from browserstack.local import Local
import os
from appium import webdriver
import json
from jsonmerge import merge
CONFIG_FILE = os.environ['CONFIG_FILE'] if 'CONFIG_FILE' in os.environ else 'run-single-test/single.json'
TASK_ID = int(os.environ['TASK_ID']) if 'TASK_ID' in os.environ else 0

with open(CONFIG_FILE) as data_file:
CONFIG = json.load(data_file)

bs_local = None

BROWSERSTACK_USERNAME = os.environ['BROWSERSTACK_USERNAME'] if 'BROWSERSTACK_USERNAME' in os.environ else CONFIG["user"]
BROWSERSTACK_ACCESS_KEY = os.environ['BROWSERSTACK_ACCESS_KEY'] if 'BROWSERSTACK_ACCESS_KEY' in os.environ else CONFIG["key"]


def start_local():
"""Code to start browserstack local before start of test."""
global bs_local
bs_local = Local()
bs_local_args = {
"key": BROWSERSTACK_ACCESS_KEY or "access_key", "forcelocal": "true"}
bs_local.start(**bs_local_args)


def stop_local():
"""Code to stop browserstack local after end of test."""
global bs_local
if bs_local is not None:
bs_local.stop()


@pytest.fixture(scope='session')
def session_capabilities():
capabilities = merge(CONFIG['environments']
[TASK_ID], CONFIG["capabilities"])
capabilities['bstack:options']['userName'] = BROWSERSTACK_USERNAME
capabilities['bstack:options']['accessKey'] = BROWSERSTACK_ACCESS_KEY
if "local" in capabilities['bstack:options'] and capabilities['bstack:options']['local']:
start_local()
return capabilities


@pytest.fixture(scope='function')
def setWebdriver(request, session_capabilities):
remoteURL = "https://hub.browserstack.com/wd/hub"
driver = webdriver.Remote(remoteURL, session_capabilities)
request.cls.driver = driver

yield driver

driver.quit()


def pytest_sessionfinish(session, exitstatus):
stop_local()
36 changes: 36 additions & 0 deletions android/pavement.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from paver.easy import *
from paver.setuputils import setup
from multiprocess import Process
import platform
import json

def run_py_test(config, task_id=0):
if platform.system() == "Windows":
if(config=="local"):
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))
elif(config == "parallel"):
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))
else:
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))

else:
if(config=="local"):
sh('CONFIG_FILE=run-local-test/%s.json TASK_ID=%s pytest -s run-local-test/tests/*.py' % (config, task_id))
elif(config == "parallel"):
sh('CONFIG_FILE=run-parallel-test/%s.json TASK_ID=%s pytest -s run-parallel-test/tests/*.py -n 2' % (config, task_id))
else:
sh('CONFIG_FILE=run-single-test/%s.json TASK_ID=%s pytest -s run-single-test/tests/*.py' % (config, task_id))

@task
@consume_nargs(1)
def run(args):
"""Run single, local and parallel test using different config."""
jobs = []
config_file = 'run-%s-test/%s.json' % (args[0], args[0])
with open(config_file) as data_file:
CONFIG = json.load(data_file)
environments = CONFIG['environments']
for i in range(len(environments)):
p = Process(target=run_py_test, args=(args[0], i))
jobs.append(p)
p.start()
22 changes: 22 additions & 0 deletions android/run-local-test/local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"user": "BROWSERSTACK_USERNAME",
"key": "BROWSERSTACK_ACCESS_KEY",
"capabilities": {
"app" : "bs://<app-id>",
"bstack:options": {
"projectName": "Pytest Android Project",
"buildName": "browserstack-build-1",
"sessionName": "BStack local_test",
"local": "true",
"debug": "true",
"networkLogs": "true"
}
},
"environments": [
{
"platformName": "android",
"platformVersion": "9.0",
"deviceName": "Google Pixel 3"
}
]
}
38 changes: 38 additions & 0 deletions android/run-local-test/tests/local_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from browserstack.local import Local
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import pytest
from selenium.webdriver.common.by import By


@pytest.mark.usefixtures('setWebdriver')
class TestSample:

def test_example(self):
test_button = WebDriverWait(self.driver, 30).until(
EC.element_to_be_clickable(
(AppiumBy.ID, "com.example.android.basicnetworking:id/test_action"))
)

test_button.click()

time.sleep(5)

test_element = None
search_results = self.driver.find_elements(AppiumBy.CLASS_NAME, "android.widget.TextView")
print(len(search_results))
for result in search_results:
if "Up and running" in result.text:
test_element = result

if test_element is None:
self.driver.execute_script(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Cannot find the needed TextView element from app"}}')
else:
self.driver.execute_script(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Test Passed Successfully"}}')


Comment thread
princebaretto99 marked this conversation as resolved.
27 changes: 27 additions & 0 deletions android/run-parallel-test/parallel.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"user": "BROWSERSTACK_USERNAME",
"key": "BROWSERSTACK_ACCESS_KEY",
"capabilities": {
"app" : "bs://<app-id>",
"bstack:options": {
"projectName": "Pytest Android Project",
"buildName": "browserstack-build-1",
"sessionName": "BStack parallel_test",
"local": false,
"debug": "true",
"networkLogs": "true"
}
},
"environments": [
{
"platformName": "android",
"platformVersion": "9.0",
"deviceName": "Google Pixel 3"
},
{
"platformName": "android",
"platformVersion": "11.0",
"deviceName": "Samsung Galaxy A52"
}
]
}
34 changes: 34 additions & 0 deletions android/run-parallel-test/tests/test_sample_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from browserstack.local import Local
from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import pytest
from selenium.webdriver.common.by import By

@pytest.mark.usefixtures('setWebdriver')
class TestSample:

def test_example(self):
search_element = WebDriverWait(self.driver, 30).until(
EC.element_to_be_clickable(
(AppiumBy.ACCESSIBILITY_ID, "Search Wikipedia"))
)

search_element.click()
search_input = WebDriverWait(self.driver, 30).until(
EC.element_to_be_clickable(
(AppiumBy.ID, "org.wikipedia.alpha:id/search_src_text"))
)
search_input.send_keys("BrowserStack")
time.sleep(5)
search_results = self.driver.find_elements(
AppiumBy.CLASS_NAME, "android.widget.TextView")

if(len(search_results) > 0):
self.driver.execute_script(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Test Passed Successfully"}}')
else:
self.driver.execute_script(
'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Test Failed"}}')
Loading