#  Example Appium Scripts for Android Mobile Application Tests

These Appium scripts for Android mobile application tests can help streamline your testing process.

For Example Purposes Only

The code in these scripts is provided on an "AS-IS” basis without warranty of any kind, either express or implied, including without limitation any implied warranties of condition, uninterrupted use, merchantability, fitness for a particular purpose, or non-infringement. Your tests and testing environments may require you to modify these scripts. Issues regarding these scripts should be submitted through GitHub. These scripts are not maintained by Sauce Labs Support.

These examples employ the page object model to run tests on emulators and simulators. Feel free to clone these scripts directly from GitHub, and follow the instructions in the README file.

### Page Objects

This object represents a single view/page in the sample application. Click below to see the script:  
  


GuineaPigPage.java

**GuineaPigPage.java** (source from Sauce Labs Training Java)
    
    
    package example.android.Pages;
    
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class GuineaPigPage {
    
        @FindBy(id = "Heading1_1")
        private WebElement h1Text;
    
        @FindBy(id = "i_am_a_link")
        private WebElement theActiveLink;
    
        @FindBy(id = "your_comments")
        private WebElement yourComments;
    
        @FindBy(id = "comments")
        private WebElement commentsTextInput;
    
        @FindBy(id = "submit")
        private WebElement submitButton;
    
        public WebDriver driver;
    
        public GuineaPigPage(WebDriver driver) {
            this.driver = driver;
            PageFactory.initElements(driver, this);
        }
    
        public void submitComment(String text) {
            this.commentsTextInput.click();
            this.commentsTextInput.sendKeys(text);
            hideKeyboard();
            this.submitButton.click();
        }
    
        public String getSubmittedCommentText() {
            return this.yourComments.getText();
        }
    
        public void followLink() {
            this.theActiveLink.click();
        }
    
        public boolean isOnPage() {
            try {
                getSubmittedCommentText();
                return true;
            } catch (NoSuchElementException ex) {
                return false;
            }
        }
    
        /**
         * This method only work for this page and assumes the app supports keyboard hide on click-away.
         */
        public void hideKeyboard() {
            this.h1Text.click();
        }
    }

###   
Test Objects

These object represent the individual tests, as well as the prerequisite and postrequisite test tasks (TestBase.java). Click on any of the text below to see the scripts:  
  


TestBase.java

**TestBase.java** (source from Sauce Labs Training Java)
    
    
    package example.android.Tests;
    
    // import Sauce TestNG helper libraries
    
    import com.saucelabs.common.SauceOnDemandAuthentication;
    import com.saucelabs.common.SauceOnDemandSessionIdProvider;
    import com.saucelabs.testng.SauceOnDemandAuthenticationProvider;
    import com.saucelabs.testng.SauceOnDemandTestListener;
    import io.appium.java_client.android.AndroidDriver;
    import org.openqa.selenium.MutableCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Listeners;
    
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.rmi.UnexpectedException;
    
    // import testng annotations
    // import java libraries
    
    /**
     * Simple TestNG test which demonstrates being instantiated via a DataProvider in order to supply multiple browser combinations.
     *
     * @author Neil Manvar
     */
    @Listeners({SauceOnDemandTestListener.class})
    public class TestBase implements SauceOnDemandSessionIdProvider, SauceOnDemandAuthenticationProvider {
    
        public String seleniumURI = "@ondemand.saucelabs.com:443";
        public String buildTag = System.getenv("BUILD_TAG");
        public String username = System.getenv("SAUCE_USERNAME");
        public String accesskey = System.getenv("SAUCE_ACCESS_KEY");
        public String app = "https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/android/GuineaPigApp-debug.apk?raw=true";
        //public String app = "../../../../../../resources/android/GuineaPigApp-debug.apk";
    
        /**
         * Constructs a {@link SauceOnDemandAuthentication} instance using the supplied user name/access key.  To use the authentication
         * supplied by environment variables or from an external file, use the no-arg {@link SauceOnDemandAuthentication} constructor.
         */
        public SauceOnDemandAuthentication authentication = new SauceOnDemandAuthentication(username, accesskey);
    
        /**
         * ThreadLocal variable which contains the  {@link AndroidDriver} instance which is used to perform browser interactions with.
         */
        private ThreadLocal<AndroidDriver> androidDriver = new ThreadLocal<AndroidDriver>();
    
        /**
         * ThreadLocal variable which contains the Sauce Job Id.
         */
        private ThreadLocal<String> sessionId = new ThreadLocal<String>();
    
        /**
         * DataProvider that explicitly sets the browser combinations to be used.
         *
         * @param testMethod
         * @return Two dimensional array of objects with browser, version, and platform information
         */
        @DataProvider(name = "hardCodedBrowsers", parallel = true)
        public static Object[][] sauceBrowserDataProvider(Method testMethod) {
            return new Object[][]{
                    new Object[]{"Android", "Samsung Galaxy Tab S3 GoogleAPI Emulator", "8.1", "1.9.1", "portrait"},
                    new Object[]{"Android", "Samsung Galaxy S9 Plus FHD GoogleAPI Emulator", "8.1", "1.9.1", "portrait"}
            };
        }
    
        /**
         * @return the {@link AndroidDriver} for the current thread
         */
        public AndroidDriver getAndroidDriver() {
            return androidDriver.get();
        }
    
        /**
         * @return the Sauce Job id for the current thread
         */
        public String getSessionId() {
            return sessionId.get();
        }
    
        /**
         * @return the {@link SauceOnDemandAuthentication} instance containing the Sauce username/access key
         */
        @Override
        public SauceOnDemandAuthentication getAuthentication() {
            return authentication;
        }
    
        /**
         * Constructs a new {@link AndroidDriver} instance which is configured to use the capabilities defined by the browser,
         * version and os parameters, and which is configured to run against ondemand.saucelabs.com, using
         * the username and access key populated by the {@link #authentication} instance.
         *
         * @param platformName      name of the platformName. (Android, iOS, etc.)
         * @param deviceName        name of the device
         * @param platformVersion   Os version of the device
         * @param appiumVersion     appium version
         * @param deviceOrientation device orientation
         * @return
         * @throws MalformedURLException if an error occurs parsing the url
         */
        protected void createDriver(
                String platformName,
                String deviceName,
                String platformVersion,
                String appiumVersion,
                String deviceOrientation,
                String methodName)
                throws MalformedURLException, UnexpectedException {
            MutableCapabilities capabilities = new MutableCapabilities();
            capabilities.setCapability("platformName", platformName);
            capabilities.setCapability("platformVersion", platformVersion);
            capabilities.setCapability("deviceName", deviceName);
            capabilities.setCapability("browserName", "");
            capabilities.setCapability("deviceOrientation", deviceOrientation);
            capabilities.setCapability("appiumVersion", appiumVersion);
            capabilities.setCapability("name", methodName);
            capabilities.setCapability("app", app);
            capabilities.setCapability("build", "Java-TestNG-Appium-Android");
    
            if (buildTag != null) {
                capabilities.setCapability("build", buildTag);
            }
    
            // Launch remote browser and set it as the current thread
            androidDriver.set(new AndroidDriver(
                    new URL("https://" + authentication.getUsername() + ":" + authentication.getAccessKey() + seleniumURI + "/wd/hub"),
                    capabilities));
    
            String id = ((RemoteWebDriver) getAndroidDriver()).getSessionId().toString();
            sessionId.set(id);
        }
    
        /**
         * Method that gets invoked after test.
         * Dumps browser log and
         * Closes the browser
         */
        @AfterMethod
        public void tearDown() throws Exception {
    
            //Gets browser logs if available.
            androidDriver.get().quit();
        }
    }

FollowLinkTest.java

**FollowLinkTest.java** (source from Sauce Labs Training Java)
    
    
    package example.android.Tests;
    
    import example.android.Pages.GuineaPigPage;
    import org.openqa.selenium.InvalidElementStateException;
    import org.openqa.selenium.WebDriver;
    import org.testng.Assert;
    import org.testng.annotations.Test;
    
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.rmi.UnexpectedException;
    
    /**
     * Created by mehmetgerceker on 12/7/15.
     * Updated by spider@saucelabs.com on 10/8/19.
     */
    
    public class FollowLinkTest extends TestBase {
    
        /**
         * Runs a simple test verifying link can be followed.
         *
         * @throws InvalidElementStateException
         */
        @Test(dataProvider = "hardCodedBrowsers")
        public void verifyLinkTest(String platformName,
                                   String deviceName,
                                   String platformVersion,
                                   String appiumVersion,
                                   String deviceOrientation,
                                   Method method)
                throws MalformedURLException, InvalidElementStateException, UnexpectedException {
    
            //create webdriver session
            this.createDriver(platformName, deviceName, platformVersion, appiumVersion, deviceOrientation, method.getName());
            WebDriver driver = this.getAndroidDriver();
    
            GuineaPigPage page = new GuineaPigPage(driver);
    
            page.followLink();
    
            Assert.assertFalse(page.isOnPage());
        }
    
    }

TextInputTest.java

**TextInputTest.java** (source from Sauce Labs Training Java)
    
    
    package example.android.Tests;
    
    import example.android.Pages.GuineaPigPage;
    import org.openqa.selenium.InvalidElementStateException;
    import org.openqa.selenium.WebDriver;
    import org.testng.Assert;
    
    import java.lang.reflect.Method;
    import java.net.MalformedURLException;
    import java.rmi.UnexpectedException;
    import java.util.UUID;
    
    
    /**
     * Created by mehmetgerceker on 12/7/15.
     */
    
    public class TextInputTest extends TestBase {
    
        /**
         * Runs a simple test verifying if the comment input is functional.
         * @throws InvalidElementStateException
         */
        @org.testng.annotations.Test(dataProvider = "hardCodedBrowsers")
        public void verifyCommentInputTest(String platformName,
                                           String deviceName,
                                           String platformVersion,
                                           String appiumVersion,
                                           String deviceOrientation,
                                           Method method)
                throws MalformedURLException, InvalidElementStateException, UnexpectedException {
    
            this.createDriver(platformName, deviceName, platformVersion, appiumVersion, deviceOrientation, method.getName());
            WebDriver driver = this.getAndroidDriver();
    
            String commentInputText = UUID.randomUUID().toString();
    
            GuineaPigPage page = new GuineaPigPage(driver);
    
            page.submitComment(commentInputText);
    
            Assert.assertTrue(page.getSubmittedCommentText().contains(commentInputText));
        }
    
    }

These examples employ the page object model using WebDriverIO and the Mocha \+ Chai test framework to run tests on emulators and simulators. Feel free to clone these scripts directly from GitHub, and follow the instructions in the README file.

### WebDriverIO Config

This script represents the prerequisite and postrequisite test tasks. Click below to see the script:

wdio.conf.js

**wdio.conf.js** (source from Sauce Labs Training JavaScript)
    
    
    exports.config = {
        //
        // ====================
        // Runner Configuration
        // ====================
        //
        // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
        // on a remote machine).
        //runner: 'local',
        user: process.env.SAUCE_USERNAME,
        key: process.env.SAUCE_ACCESS_KEY,
        region: 'us',
        sauceConnect: false,
        //
        // Override default path ('/wd/hub') for chromedriver service.
        //path: '/',
        //
        // ==================
        // Specify Test Files
        // ==================
        // Define which test specs should run. The pattern is relative to the directory
        // from which `wdio` was called. Notice that, if you are calling `wdio` from an
        // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
        // directory is where your package.json resides, so `wdio` will be called from there.
        //
        specs: [
            './test/specs/**/*.js'
        ],
        // Patterns to exclude.
        exclude: [
            // 'path/to/excluded/files'
        ],
        //
        // ============
        // Capabilities
        // ============
        // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
        // time. Depending on the number of capabilities, WebdriverIO launches several test
        // sessions. Within your capabilities you can overwrite the spec and exclude options in
        // order to group specific specs to a specific capability.
        //
        // First, you can define how many instances should be started at the same time. Let's
        // say you have 3 different capabilities (Chrome, Firefox, and Safari) and you have
        // set maxInstances to 1; wdio will spawn 3 processes. Therefore, if you have 10 spec
        // files and you set maxInstances to 10, all spec files will get tested at the same time
        // and 30 processes will get spawned. The property handles how many capabilities
        // from the same test should run tests.
        //
        maxInstances: 10,
        //
        // If you have trouble getting all important capabilities together, check out the
        // Sauce Labs platform configurator - a great tool to configure your capabilities:
        // https://docs.saucelabs.com/reference/platforms-configurator
        //
        capabilities: [
            // maxInstances can get overwritten per capability. So if you have an in-house Selenium
            // grid with only 5 firefox instances available you can make sure that not more than
            // 5 instances get started at a time.
            //
            // If outputDir is provided WebdriverIO can capture driver session logs
            // it is possible to configure which logTypes to include/exclude.
            // excludeDriverLogs: ['*'], // pass '*' to exclude all driver session logs
            // excludeDriverLogs: ['bugreport', 'server'],
            {
                browserName: '',
                appiumVersion: '1.9.1',
                deviceName: 'Samsung Galaxy Tab A 10 GoogleAPI Emulator',
                deviceOrientation: 'portrait',
                platformVersion: '8.1',
                platformName: 'Android',
                app: 'https://github.com/appium/sample-code/blob/master/sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk?raw=true',
                waitforTimeout: 300,
                commandTimeout: 300,
                name: 'menu-test.js',
                build: 'Sample WDIO5 Appium Tests'
            }, {
                browserName: '',
                appiumVersion: '1.9.1',
                deviceName: 'Google Pixel GoogleAPI Emulator',
                deviceOrientation: 'portrait',
                platformVersion: '7.1',
                platformName: 'Android',
                app: 'https://github.com/appium/sample-code/blob/master/sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk?raw=true',
                waitforTimeout: 300,
                commandTimeout: 300,
                name: 'menu-test.js',
                build: 'Sample WDIO5 Appium Tests'
            }
        ],
        //
        // ===================
        // Test Configurations
        // ===================
        // Define all options that are relevant for the WebdriverIO instance here
        //
        // Level of logging verbosity: trace | debug | info | warn | error | silent
        sync: true,
        logLevel: 'info',
        //
        // Set specific log levels per logger
        // loggers:
        // - webdriver, webdriverio
        // - @wdio/applitools-service, @wdio/browserstack-service, @wdio/devtools-service, @wdio/sauce-service
        // - @wdio/mocha-framework, @wdio/jasmine-framework
        // - @wdio/local-runner, @wdio/lambda-runner
        // - @wdio/sumologic-reporter
        // - @wdio/cli, @wdio/config, @wdio/sync, @wdio/utils
        // Level of logging verbosity: trace | debug | info | warn | error | silent
        // logLevels: {
        //     webdriver: 'info',
        //     '@wdio/applitools-service': 'info'
        // },
        //
        // If you only want to run your tests until a specific amount of tests have failed use
        // bail (default is 0 - don't bail, run all tests).
        bail: 0,
        //
        // Set a base URL in order to shorten url command calls. If your `url` parameter starts
        // with `/`, the base url gets prepended, not including the path portion of your baseUrl.
        // If your `url` parameter starts without a scheme or `/` (like `some/path`), the base url
        // gets prepended directly.
        baseUrl: 'http://saucelabs.github.io',
        //
        // Default timeout for all waitFor* commands.
        waitforTimeout: 10000,
        //
        // Default timeout in milliseconds for request
        // if Selenium Grid doesn't send response
        connectionRetryTimeout: 90000,
        //
        // Default request retries count
        connectionRetryCount: 3,
        //
        // Test runner services
        // Services take over a specific job you don't want to take care of. They enhance
        // your test setup with almost no effort. Unlike plugins, they don't add new
        // commands. Instead, they hook themselves up into the test process.
        //services: ['chromedriver'],
        //port: 4723,
        services:
            ['sauce'],
    
        // Framework you want to run your specs with.
        // The following are supported: Mocha, Jasmine, and Cucumber
        // see also: https://webdriver.io/docs/frameworks.html
        //
        // Make sure you have the wdio adapter package for the specific framework installed
        // before running any tests.
        // appium: {
        //     command: "appium",
        // },
        framework: 'mocha',
        //
        // The number of times to retry the entire specfile when it fails as a whole
        // specFileRetries: 1,
        //
        // Test reporter for stdout.
        // The only one supported by default is 'dot'
        // see also: https://webdriver.io/docs/dot-reporter.html
        reporters: ['spec'],
     
        //
        // Options to be passed to Mocha.
        // See the full list at http://mochajs.org/
        mochaOpts: {
            ui: 'bdd',
            timeout: 60000
        },
        //
        // =====
        // Hooks
        // =====
        // WebdriverIO provides several hooks you can use to interfere with the test process in order to enhance
        // it and to build services around it. You can either apply a single function or an array of
        // methods to it. If one of them returns with a promise, WebdriverIO will wait until that promise got
        // resolved to continue.
        /**
         * Gets executed once before all workers get launched.
         * @param {Object} config wdio configuration object
         * @param {Array.<Object>} capabilities list of capabilities details
         */
        // onPrepare: function (config, capabilities) {
        // },
        /**
         * Gets executed just before initialising the webdriver session and test framework. It allows you
         * to manipulate configurations depending on the capability or spec.
         * @param {Object} config wdio configuration object
         * @param {Array.<Object>} capabilities list of capabilities details
         * @param {Array.<String>} specs List of spec file paths that are to be run
         */
        // beforeSession: function (config, capabilities, specs) {
        // },
        /**
         * Gets executed before test execution begins. At this point you can access to all global
         * variables like `browser`. It is the perfect place to define custom commands.
         * @param {Array.<Object>} capabilities list of capabilities details
         * @param {Array.<String>} specs List of spec file paths that are to be run
         */
        // before: function (capabilities, specs) {
        //     var chai = require('chai');
        //     var chaiWebDriver = require('chai-webdriverio').default;
        //     chai.use(chaiWebDriver(browser));
        //
        //     global.expect = chai.expect;
        // },
        /**
         * Runs before a WebdriverIO command gets executed.
         * @param {String} commandName hook command name
         * @param {Array} args arguments that command would receive
         */
        // beforeCommand: function (commandName, args) {
        // },
        /**
         * Hook that gets executed before the suite starts
         * @param {Object} suite suite details
         */
        // beforeSuite: function (suite) {
        // },
        /**
         * Function to be executed before a test (in Mocha/Jasmine) starts.
         */
        // beforeTest: function (test, context) {
        // },
        /**
         * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
         * beforeEach in Mocha)
         */
        // beforeHook: function (test, context) {
        // },
        /**
         * Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
         * afterEach in Mocha)
         */
        // afterHook: function (test, context, { error, result, duration, passed, retries }) {
        // },
        /**
         * Function to be executed after a test (in Mocha/Jasmine).
         */
        // afterTest: function(test, context, { error, result, duration, passed, retries }) {
        // },
    
    
        /**
         * Hook that gets executed after the suite has ended
         * @param {Object} suite suite details
         */
        // afterSuite: function (suite) {
        // },
        /**
         * Runs after a WebdriverIO command gets executed
         * @param {String} commandName hook command name
         * @param {Array} args arguments that command would receive
         * @param {Number} result 0 - command success, 1 - command error
         * @param {Object} error error object if any
         */
        // afterCommand: function (commandName, args, result, error) {
        // },
        /**
         * Gets executed after all tests are done. You still have access to all global variables from
         * the test.
         * @param {Number} result 0 - test pass, 1 - test fail
         * @param {Array.<Object>} capabilities list of capabilities details
         * @param {Array.<String>} specs List of spec file paths that ran
         */
        // after: function (result, capabilities, specs) {
        // },
        /**
         * Gets executed right after terminating the webdriver session.
         * @param {Object} config wdio configuration object
         * @param {Array.<Object>} capabilities list of capabilities details
         * @param {Array.<String>} specs List of spec file paths that ran
         */
        // afterSession: function (config, capabilities, specs) {
        // },
        /**
         * Gets executed after all workers got shut down and the process is about to exit. An error
         * thrown in the onComplete hook will result in the test run failing.
         * @param {Object} exitCode 0 - success, 1 - fail
         * @param {Object} config wdio configuration object
         * @param {Array.<Object>} capabilities list of capabilities details
         * @param {<Object>} results object containing test results
         */
        // onComplete: function(exitCode, config, capabilities, results) {
        // },
        /**
        * Gets executed when a refresh happens.
        * @param {String} oldSessionId session ID of the old session
        * @param {String} newSessionId session ID of the new session
        */
        //onReload: function(oldSessionId, newSessionId) {
        //}
    };

###   
Page Objects

These scripts represent each view/page in the sample application. Click below to see the script:  
  


page.js

**page.js** (source from Sauce Labs Training JavaScript)
    
    
    /**
     * Created by titusfortner on 11/23/16.
     */
    function Page () {
    }
    
    Page.prototype.open = function (path) {
        browser.url('/' + path)
    };
    
    module.exports = new Page();

home.page.js

**home.page.js** (source from Sauce Labs Training JavaScript)
    
    
    /**
     * Created by titusfortner on 11/23/16.
     */
    var Page = require('./page');
    
    var HomePage = Object.create(Page, {
        graphicsTab: {
            get: function () {
                return browser.$(`~Graphics`);
            }
        },
    
        click: {
            value: function (tabName) {
                if (tabName === "Graphics") {
                    this.graphicsTab.click();
    
                } else {
                    throwError("Not implemented");
                }
    
            }
        }
    
    });
    
    module.exports = HomePage;

menu.page.js

**menu.page.js** (source from Sauce Labs Training JavaScript)
    
    
    /**
     * Created by titusfortner on 11/23/16.
     */
    var Page = require('./page');
    
    var MenuPage = Object.create(Page, {
        arcsEntry: {
            get: function () {
                return browser.$(`~Arcs`);
            }
        }
    });
    
    module.exports = MenuPage;

###   
Test Objects

This script represents the individual tests. Click below to see the script:  
  


menu-test.js

**menu-test.js** (source from Sauce Labs Training JavaScript)
    
    
    /**
     * Created by jamestacker on 11/20/19.
     */
    const expect = require('chai').expect;
    const HomePage = require('../../pages/home.page'),
        MenuPage = require('../../pages/menu.page');
    
    describe('Mocha Spec Sync example', function() {
        it("verify Arcs entry in menu", function() {
            HomePage.click("Graphics");
            expect(MenuPage.arcsEntry.getAttribute('name')).to.equal('Arcs');
        });
    });

Use these Python test frameworks to run tests on real devices, and emulators and simulators.

These examples use the pytest test framework to run tests on real devices. Feel free to clone these scripts directly from GitHub, and follow the instructions in the README file.

### Python Config

This script initializes the test fixtures, as well as the prerequisite and post-requisite test tasks.

conftest.py

Not found

Could not read the file selenium-examples/pytest/emusim/conftest.py

### Test Objects

These scripts represents the individual test. Click below to see the script(s):

test_add_to_cart.py

**test_add_to_cart.py** (source from Sauce Labs Training Python)
    
    
    import pytest
    
    
    def test_add_to_cart(emusim_driver):
        emusim_driver.get('https://www.saucedemo.com/inventory.html')
        emusim_driver.find_element_by_class_name('btn_primary').click()
    
        assert emusim_driver.find_element_by_class_name('shopping_cart_badge').text == '1'
    
        emusim_driver.get('https://www.saucedemo.com/cart.html')
        expected = emusim_driver.find_elements_by_class_name('inventory_item_name')
        assert len(expected) == 1
    
    def test_add_two_to_cart(emusim_driver):
        emusim_driver.get('https://www.saucedemo.com/inventory.html')
        emusim_driver.find_element_by_class_name('btn_primary').click()
        emusim_driver.find_element_by_class_name('btn_primary').click()
    
        assert emusim_driver.find_element_by_class_name('shopping_cart_badge').text == '2'
    
        emusim_driver.get('https://www.saucedemo.com/cart.html')
        expected = emusim_driver.find_elements_by_class_name('inventory_item_name')
        assert len(expected) == 2

test_login_fail.py

**test_login_fail.py** (source from Sauce Labs Training Python)
    
    
    import pytest
    
    
    def test_valid_crentials_login(emusim_driver):
        emusim_driver.get('https://www.saucedemo.com')
    
        emusim_driver.find_element_by_id('user-name').send_keys('locked_out_user')
        emusim_driver.find_element_by_id('password').send_keys('secret_sauce')
        emusim_driver.find_element_by_css_selector('.btn_action').click()
    
        assert emusim_driver.find_element_by_css_selector('.error-button').is_displayed()

test_login_success.py

**test_login_success.py** (source from Sauce Labs Training Python)
    
    
    import pytest
    
    
    def test_valid_crentials_login(emusim_driver):
        emusim_driver.get('https://www.saucedemo.com')
    
        emusim_driver.find_element_by_id('user-name').send_keys('standard_user')
        emusim_driver.find_element_by_id('password').send_keys('secret_sauce')
        emusim_driver.find_element_by_css_selector('.btn_action').click()
    
        assert "/inventory.html" in emusim_driver.current_url

### Python Config

This script initializes the test fixtures, as well as the prerequisite and post-requisite test tasks.

conftest.py

Not found

Could not read the file appium-examples/pytest/rdc/android/conftest.py

### Test Objects

These scripts represents the individual tests. Click below to see the script:

test_invalid_login.py

**test_invald_login.py** (source from Sauce Labs Training Python)
    
    
    def test_blank_credentials(android_up_driver):
        android_up_driver.find_element_by_accessibility_id("test-Username").send_keys("")
        android_up_driver.find_element_by_accessibility_id("test-Password").send_keys("")
        android_up_driver.find_element_by_accessibility_id("test-LOGIN").click()
    
        assert android_up_driver.find_element_by_accessibility_id("test-Error message").is_displayed()

test_valid_login.py

**test_valid_login.py** (source from Sauce Labs Training Python)
    
    
    def test_standard_user(android_up_driver):
        android_up_driver.find_element_by_accessibility_id("test-Username").send_keys("standard_user")
        android_up_driver.find_element_by_accessibility_id("test-Password").send_keys("secret_sauce")
        android_up_driver.find_element_by_accessibility_id("test-LOGIN").click()
    
        assert android_up_driver.find_element_by_accessibility_id("test-PRODUCTS").is_displayed()

These examples employ the page object model and use either the RSpec or Cucumber test frameworks to run tests on emulators and simulators. Feel free to clone these scripts directly from GitHub, and follow the instructions in the README file.

Click here for the RSpec example...

### Rakefile

This file initializes the test capabilities, as well as the prerequisite and postrequisite test tasks:

Rakefile

**Rakefile** (source from Sauce Labs Training Ruby)
    
    
    def run_tests(deviceName, platformName, platformVersion, app)
      system("deviceName=\"#{deviceName}\" platformName=\"#{platformName}\" platformVersion=\"#{platformVersion}\" app=\"#{app}\" parallel_split_test spec")
    end
    
    task :Andoid_Emulator_Phone_5_1 do
      run_tests('Android Emulator', 'Android', '5.1', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true')
    end
    
    task :Andoid_Emulator_Tablet_5_1 do
      run_tests('Android Emulator', 'Android', '5.1', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true')
    end
    
    task :Galaxy_S8_Emulator do
      run_tests('Samsung Galaxy S8 HD GoogleAPI Emulator', 'Android', '7.0', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true')
    end
    
    task :Galaxy_S6_Emulator do
      run_tests('Samsung Galaxy S6 GoogleAPI Emulator', 'Android', '7.0', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true')
    end
    
    task :iPhone_6_Simulator do
      run_tests('iPhone 6 Simulator', 'iOS', '10.3', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true')
    end
    
    task :iPhone_7_Simulator do
      run_tests('iPhone 7 Simulator', 'iOS', '12.0', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true')
    end
    
    task :iPad_Air_Simulator do
      run_tests('iPad Air Simulator', 'iOS', '11.2', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true')
    end
    
    task :iPad_Simulator do
      run_tests('iPad (6th generation) Simulator', 'iOS', '12.0', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true')
    end
    
    multitask :test_sauce => [
        :Andoid_Emulator_Phone_5_1,
        :Galaxy_S8_Emulator,
        :Andoid_Emulator_Tablet_5_1,
        :Galaxy_S6_Emulator,
        :iPhone_6_Simulator,
        :iPhone_7_Simulator,
        :iPad_Air_Simulator,
        :iPad_Simulator,
    
    ] do
      puts 'Running automation'
    end

### Page Objects

These scripts represent the individual views/pages of the sample application:

app_object.rb

**app_object.rb** (source from Sauce Labs Training Ruby)
    
    
    require_relative "../spec/spec_helper"
    
    class GuineaPigAppPage
      attr_accessor :driver
      def initialize(driver)
        @driver = driver
      end
    
      # Elements
    
      def textInput
        @driver.find_element(:id, "i_am_a_textbox")
      end
    
      def emailTextInput
        @driver.find_element(:id, "fbemail")
      end
    
    end

### Spec Objects

These scripts represents the individual tests, as well as a Sauce Labs utility helper:

comment_test_spec.rb

**app_object.rb** (source from Sauce Labs Training Ruby)
    
    
    require_relative "../spec/spec_helper"
    
    class GuineaPigAppPage
      attr_accessor :driver
      def initialize(driver)
        @driver = driver
      end
    
      # Elements
    
      def textInput
        @driver.find_element(:id, "i_am_a_textbox")
      end
    
      def emailTextInput
        @driver.find_element(:id, "fbemail")
      end
    
    end

spec_helper.rb

**app_object.rb** (source from Sauce Labs Training Ruby)
    
    
    require_relative "../spec/spec_helper"
    
    class GuineaPigAppPage
      attr_accessor :driver
      def initialize(driver)
        @driver = driver
      end
    
      # Elements
    
      def textInput
        @driver.find_element(:id, "i_am_a_textbox")
      end
    
      def emailTextInput
        @driver.find_element(:id, "fbemail")
      end
    
    end

Click here for the Cucumber example...

### Rakefile

This file initializes the prerequisite and postrequisite test tasks:

Rakefile

**Rakefile** (source from Sauce Labs Training Ruby)
    
    
    def run_tests(deviceName, platformName, platformVersion, app, junit)
      system("deviceName=\"#{deviceName}\" platformName=\"#{platformName}\" platformVersion=\"#{platformVersion}\" app=\"#{app}\" parallel_cucumber features -n 20")
    end
    
    task :Andoid_Emulator_Phone_5_1 do
      run_tests('Android Emulator', 'Android', '5.1', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true', 'junit_reports/Andoid_Emulator_Phone_5_1')
    end
    
    task :Andoid_Emulator_Tablet_5_1 do
      run_tests('Android Emulator', 'Android', '5.1', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true', 'junit_reports/Andoid_Emulator_Tablet_5_1')
    end
    
    task :Galaxy_S8_Emulator do
      run_tests('Samsung Galaxy S8 HD GoogleAPI Emulator', 'Android', '7.0', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true', 'junit_reports/Galaxy_S8_Emulator')
    end
    
    task :Galaxy_S6_Emulator do
      run_tests('Samsung Galaxy S6 GoogleAPI Emulator', 'Android', '7.0', 'https://github.com/saucelabs-sample-test-frameworks/Java-Junit-Appium-Android/blob/master/resources/GuineaPigApp-debug.apk?raw=true', 'junit_reports/Galaxy_S6_Emulator')
    end
    
    task :iPhone_6_Simulator do
      run_tests('iPhone 6 Simulator', 'iOS', '10.3', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true', 'junit_reports/iPhone_6_Simulator')
    end
    
    task :iPhone_7_Simulator do
      run_tests('iPhone 7 Simulator', 'iOS', '12.0', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true', 'junit_reports/iPhone_5s_Simulator')
    end
    
    task :iPad_Air_Simulator do
      run_tests('iPad Air Simulator', 'iOS', '11.2', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true', 'junit_reports/iPad_Air_Simulator')
    end
    
    task :iPad_Simulator do
      run_tests('iPad (6th generation) Simulator', 'iOS', '12.0', 'https://github.com/saucelabs-training/demo-java/blob/master/appium-example/resources/ios/SauceGuineaPig-sim-debug.app.zip?raw=true', 'junit_reports/iPad_Simulator')
    end
    
    multitask :test_sauce => [
        :Andoid_Emulator_Phone_5_1,
        :Galaxy_S8_Emulator,
        :Andoid_Emulator_Tablet_5_1,
        :Galaxy_S6_Emulator,
        :iPhone_6_Simulator,
        :iPhone_7_Simulator,
        :iPad_Air_Simulator,
        :iPad_Simulator,
    
    ] do
      puts 'Running automation'
    end

### Environment Object

This script pulls the test capabilities for each device combo from the rake tasks; it also initializes the remote web driver object:

env.rb

**env.rb** (source from Sauce Labs Training Ruby)
    
    
    require 'appium_lib'
    require 'sauce_whisk'
    require 'rspec'
    
    Before do | scenario |
      # need to configure env variables for browser
      caps = {
          caps: {
              platformVersion: "#{ENV['platformVersion']}",
              deviceName: "#{ENV['deviceName']}",
              platformName: "#{ENV['platformName']}",
              app: "#{ENV['app']}",
              deviceOrientation: 'portrait',
              name: "#{scenario.feature.name} - #{scenario.name}",
              appiumVersion: '1.9.1',
              browserName: '',
              build: 'Appium-Ruby-Cucumber EmuSim Examples'
          }
      }
    
      @driver = Appium::Driver.new(caps, true)
      @driver.start_driver
    end
    
    # "after all"
    After do | scenario |
      sessionid =  @driver.session_id
      jobname = "#{scenario.feature.name} - #{scenario.name}"
      puts "SauceOnDemandSessionID=#{sessionid} job-name=#{jobname}"
    
      @driver.driver_quit
    
      if scenario.passed?
        SauceWhisk::Jobs.pass_job sessionid
      else
        SauceWhisk::Jobs.fail_job sessionid
      end
    end

### Test Features

These scripts represents the individual behavior scenarios that we define tests for in our step definitions:

comment.feature

**comment.feature** (source from Sauce Labs Training Ruby)
    
    
    Feature: Sample Ruby Cucumber Comment Test
    
      Scenario: Add a Comment
        Given I click on the comment box
        When I enter a comment
        Then I click the send button

email.feature

**email.feature** (source from Sauce Labs Training Ruby)
    
    
    Feature: Sample Ruby Cucumber Email Test
    
      Scenario: Enter an Email Address
        Given I click on the email box
        When I enter my email address
        Then I click the submit button

### Test Step Definitions

These scripts define the specific steps our tests run in order to achieve the desired results from the test features:

comment_steps.rb

**comment_steps.rb** (source from Sauce Labs Training Ruby)
    
    
    Given /^I click on the comment box$/ do
      comment_input = @driver.find_element(:id, "comments")
      comment_input.click()
    end
    
    When /^I enter a comment$/ do
      comment_text = @driver.find_element(:id, "comments")
      comment_text.send_keys("My Exceptionally Eloquent Comment")
    end
    
    Then /^I click the send button$/ do
      submit_button = @driver.find_element(:id, "submit")
      submit_button.click()
    end

email_steps.rb

**email_steps.rb** (source from Sauce Labs Training Ruby)
    
    
    Given /^I click on the email box$/ do
      email_input = @driver.find_element(:id, "fbemail")
      email_input.click()
    end
    
    When /^I enter my email address$/ do
      email_text = @driver.find_element(:id, "fbemail")
      email_text.send_keys("example@email.com")
    end
    
    Then /^I click the submit button$/ do
      submit_button = @driver.find_element(:id, "submit")
      submit_button.click()
    end