Back to Resources

Blog

Posted September 29, 2017

Testing A Hybrid Mobile App Using Appium

quote

If you want to test hybrid mobile apps—or any other kind of app, for that matter—Appium is a great choice. In this article, I provide an Appium example of testing a hybrid mobile app built with React.

Appium’s Versatility: Mobile Testing and Beyond

First, though, a few words on why Appium is a great choice for hybrid mobile app testing. Appium is an open source automation testing framework for use with native and hybrid mobile apps. It aims to be language and framework agnostic—meaning it can work with any language and testing framework of your choice.

Once you choose a language, more often than not, Appium works with it. Appium can be used to test iOS, Android and Windows applications, even if it's hybrid. Appium aims to automate any mobile app from any language and any test framework, with full access to backend APIs and DBs from test code. It does this by using the WebDriver protocol which is a control interface that enables programs to remotely instruct the behavior of web browsers.

To show how versatile Appium is, in this article we’ll use it for a scenario that is somewhat off the beaten path: Testing a React Native hybrid app using the py.test framework.

My Hybrid Mobile App

My hybrid app is written in ReactJS, and my test cases are written in Python. They all work together by communicating with the Appium WebDriver client.

This driver connects to the Appium service that runs in the background on your local machine. Appium is so robust that you can also choose to not run the service in your local machine! You can just connect to the Sauce Labs cloud-based mobile testing platform and leave it up to them to maintain all of the emulators, simulators and real devices you would like to test against.

Getting Started with Appium

To kick things off, let's install Appium.

1
brew install libimobiledevice --HEAD
2
brew install carthage
3
npm install -g appium
4
npm install wd
5
npm install -g ios-deploy
6

I'm installing Appium on MacOS with `brew` and `node` already installed.

Now let's start the Appium service with the appium command.

You should now see:

[Appium] Welcome to Appium v1.6.3 [Appium] Appium REST http interface listener started on 0.0.0.0:4723

Connecting the Puzzle

Alright. We have Appium running. Now what?

All we have to do is write test cases in whatever language and framework we choose and connect them to Appium. I'm choosing Python and `py.test`. You can also choose Javascript and Mocha. But I prefer Python. I'll be testing a React Native hybrid mobile app compiled to both iOS (.app) and Android (.apk).

The test cases instruct Appium to fill in text boxes, click on buttons, check content on the screen, and even wait a specific amount of time for a screen to load. If at any time Appium is unable to find elements, it will throw an exception and your test fails.

Let's start testing!

Creating a React Native Hybrid Mobile App

You can fetch the dummy application from my GitHub

The app contains two text fields, one for username and one for password, and also a button to “log in.” For the purposes of this article, the login function does nothing, absolutely nothing!

Writing Tests

Let's first make sure to have `pytest` and the Python Appium Client installed. It's as simple as:

pip install pytest pip install Appium-Python-Client

Essentially, `py.test` will connect to the Appium service and launch the application, either on the simulator or physical device. You will have to provide the Appium endpoint and the location of the `.app` or `.apk` file. You can also specify the device you'd like to test it on.

Creating a Base Test Class

Let's create a base test class that handles high-level functions such as connecting to the Appium service and terminating the connection.

1
import unittest
2
from appium import webdriver
3
class AppiumTest(unittest.TestCase):
4
def setUp(self):
5
self.driver = webdriver.Remote(
6
command_executor='http://127.0.0.1:4723/wd/hub',
7
desired_capabilities={
8
'app': 'PATH_OF_.APP_FILE',
9
'platformName': 'iOS',
10
'deviceName': 'iPhone Simulator',
11
'automationName': 'XCUITest',
12
})
13
def tearDown(self):
14
self.driver.quit()

Selecting Elements

How do we tell Appium to click on this button or fill in this form? We do this by identifying the elements either with classnames, IDs, XPaths, accessibility labels, or more.

We'll use both XPaths and accessibility labels here, since React Native has not yet implemented IDs.

Finding Elements Using XPaths

You can find an element with two of its attributes: its selector and name. For example, if your TextView called “Welcome to Appium,” the selector would be “text” and “Welcome To Appium” would be used as the identifier.

driver.find_element_by_xpath('//*[@text="Welcome To Appium"]')

This selector looks for a DOM element that has a text attribute of “Welcome To Appium.”

It's no shocker that this might not be the only TextView element with “Welcome To Appium.” What happens when there are multiple elements? You can then use the function `find_elements_by_xpath`, which returns a list of the elements that match your query.

And it's also no shocker that these values undergo continuous changes. It would not be fun to rewrite tests for every minor change that happens in the app. That's where accessibility labels come in.

Finding Elements Using Accessibility Labels

A much more stable option is to find elements using their accessibility labels. These rarely get changed during development. However, in React Native, accessibility labels can only be added to View elements. The workaround is to wrap any element you will need to test in a View element.

<View accessibilityLabel="Welcome To Appium"> <Text>Welcome To Appium</Text> </View>

Do note that accessibility labels are read by screen readers, so make sure to name sensibly.

You can now access the element like this:

driver.find_elements_by_accessibility_id("Welcome To Appium")

Transitioning Between Pages

The most common thing you'll see in test cases on either Appium or Selenium is the immense number of sleep statements. This is because the test cases you write will have no knowledge or binding to a screen.

Say your application has a button on one page and a form on another. And this button is used to transition from one page to another. You will want your test case to click on a button, transition the page, and then fill in a form. However, your test case will never know that it just transitioned between two pages! The webdriver protocol can only access elements on a page, and not a page itself. Because of this, sleep for an arbitrary amount of time is very common when you expect a page to transition. However, this is very rudimentary. With Appium, we can instead instruct it to 'wait_until' an element is on a page.

Finally, Let’s Write Some Tests!

You can find all the test cases on my GitHub repo.

Here’s how it looks for an iOS React Native app:

1
import os
2
import unittest
3
import time
4
from appium import webdriver
5
import xml
6
class AppiumTest(unittest.TestCase):
7
def setUp(self):
8
self.driver = webdriver.Remote(
9
command_executor='http://127.0.0.1:4723/wd/hub',
10
desired_capabilities={
11
'app': os.path.abspath(APP_PATH),
12
'platformName': 'iOS',
13
'deviceName': 'iPhone Simulator',
14
'automationName': 'XCUITest',
15
})
16
def tearDown(self):
17
self.driver.quit()
18
def repl(self):
19
import pdb; pdb.set_trace()
20
def dump_page(self):
21
with open('appium_page.xml', 'w') as f:
22
raw = self.driver.page_source
23
if not raw:
24
return
25
source = xml.dom.minidom.parseString(raw.encode('utf8'))
26
f.write(source.toprettyxml())
27
def _get(self, text, index=None, partial=False):
28
selector = "name"
29
if text.startswith('#'):
30
elements = self.driver.find_elements_by_accessibility_id(text[1:])
31
elif partial:
32
elements = self.driver.find_elements_by_xpath('//*[contains(@%s, "%s")]' % (selector, text))
33
else:
34
elements = self.driver.find_elements_by_xpath('//*[@%s="%s"]' % (selector, text))
35
if not elements:
36
raise Exception()
37
if index:
38
return elements[index]
39
if index is None and len(elements) > 1:
40
raise IndexError('More that one element found for %r' % text)
41
return elements[0]
42
def get(self, text, *args, **kwargs):
43
''' try to get for X seconds; paper over loading waits/sleeps '''
44
timeout_seconds = kwargs.get('timeout_seconds', 10)
45
start = time.time()
46
while time.time() - start < timeout_seconds:
47
try:
48
return self._get(text, *args, **kwargs)
49
except IndexError:
50
raise
51
except:
52
pass
53
# self.wait(.2)
54
time.sleep(.2)
55
raise Exception('Could not find text %r after %r seconds' % (
56
text, timeout_seconds))
57
def wait_until(self, *args, **kwargs):
58
# only care if there is at least one match
59
return self.get(*args, index=0, **kwargs)
60
class ExampleTests(AppiumTest):
61
def test_loginError(self):
62
self.dump_page()
63
self.wait_until('Login', partial=True)
64
self.get('Please enter your email').send_keys('foo@example.com\n')
65
self.get('Please enter your password').send_keys('Password1')
66
self.driver.hide_keyboard()
67
self.get('Press me to submit', index=1).click()
68
self.wait_until('Please check your credentials')
69
assert True
70
def test_loginSuccess(self):
71
self.dump_page()
72
self.wait_until('Login', partial=True)
73
self.get('Please enter your email').send_keys('dummyemail@example.com\n')
74
self.get('Please enter your password').send_keys('121212')
75
self.driver.hide_keyboard()
76
self.get('Press me to submit', index=1).click()
77
self.wait_until('Login Successful')
78
assert True
79
def test_loginEmptyEmail(self):
80
self.dump_page()
81
self.wait_until('Login', partial=True)
82
self.get('Please enter your email').send_keys('\n')
83
self.get('Please enter your password').send_keys('121212')
84
self.driver.hide_keyboard()
85
self.get('Press me to submit', index=1).click()
86
self.wait_until('Please enter your email ID')
87
assert True
88
def test_loginEmptyPassword(self):
89
self.dump_page()
90
self.wait_until('Login', partial=True)
91
self.get('Please enter your email').send_keys('dummyemail@example.com\n')
92
self.get('Please enter your password').send_keys('')
93
self.driver.hide_keyboard()
94
self.get('Press me to submit', index=1).click()
95
self.wait_until('Please enter your password')
96
assert True
97

And here’s how it looks for an Android React Native app:

1
import os
2
import unittest
3
import time
4
from appium import webdriver
5
import xml
6
class AppiumTest(unittest.TestCase):
7
def setUp(self):
8
abs_path = os.path.abspath(APK_PATH)
9
self.driver = webdriver.Remote(
10
command_executor='http://127.0.0.1:4723/wd/hub',
11
desired_capabilities={
12
'app': os.path.abspath(abs_path),
13
'platformName': 'Android',
14
'deviceName': 'Nexus 6P API 25',
15
})
16
def tearDown(self):
17
self.driver.quit()
18
def repl(self):
19
import pdb; pdb.set_trace()
20
def dump_page(self):
21
with open('appium_page.xml', 'w') as f:
22
raw = self.driver.page_source
23
if not raw:
24
return
25
source = xml.dom.minidom.parseString(raw.encode('utf8'))
26
f.write(source.toprettyxml())
27
def _get(self, text, index=None, partial=False):
28
selector = "content-desc"
29
if text.startswith('#'):
30
elements = self.driver.find_elements_by_accessibility_id(text[0:])
31
elif partial:
32
elements = self.driver.find_elements_by_xpath('//*[contains(@%s, "%s")]' % (selector, text))
33
else:
34
elements = self.driver.find_elements_by_xpath('//*[@%s="%s"]' % (selector, text))
35
if not elements:
36
raise Exception()
37
if index:
38
return elements[index]
39
if index is None and len(elements) > 1:
40
raise IndexError('More that one element found for %r' % text)
41
return elements[0]
42
def get(self, text, *args, **kwargs):
43
timeout_seconds = kwargs.get('timeout_seconds', 10)
44
start = time.time()
45
while time.time() - start < timeout_seconds:
46
try:
47
return self._get(text, *args, **kwargs)
48
except IndexError:
49
raise
50
except:
51
pass
52
# self.wait(.2)
53
time.sleep(.2)
54
raise Exception('Could not find text %r after %r seconds' % (
55
text, timeout_seconds))
56
def wait_until(self, *args, **kwargs):
57
# only care if there is at least one match
58
return self.get(*args, index=0, **kwargs)
59
class ExampleTests(AppiumTest):
60
def test_loginError(self):
61
time.sleep(5)
62
self.dump_page()
63
self.wait_until('Please enter your email', partial=False)
64
self.get('Please enter your email').send_keys('foo@example.com\n')
65
self.get('Please enter your password').send_keys('Password1')
66
self.driver.hide_keyboard()
67
self.get('Press me to submit', index=0).click()
68
self.wait_until('Please check your credentials')
69
assert True
70
def test_loginSuccess(self):
71
time.sleep(5)
72
self.dump_page()
73
self.wait_until('Please enter your email', partial=False)
74
self.get('Please enter your email').send_keys('dummyemail@example.com\n')
75
self.get('Please enter your password').send_keys('121212')
76
self.driver.hide_keyboard()
77
self.get('Press me to submit', index=0).click()
78
self.wait_until('Login Successful')
79
assert True
80
def test_loginEmptyEmail(self):
81
time.sleep(5)
82
self.dump_page()
83
self.wait_until('Please enter your email', partial=False)
84
self.get('Please enter your email').send_keys('\n')
85
self.get('Please enter your password').send_keys('121212')
86
self.driver.hide_keyboard()
87
self.get('Press me to submit')
88

Published:
Sep 29, 2017
Share this post
Copy Share Link
© 2023 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are registered trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.