appium UI navigation issue python script - python

I'm new to python with android. I need to write python script.
basically what I want to do is when you click first view, I need to load second view. second view has button, when it press that I need to load third view.
class SimpleAndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '4.2'
desired_caps['deviceName'] = 'Android Emulator'
desired_caps['app'] = PATH(
'mypath/aaa.apk'
)
desired_caps['appPackage'] = 'com.xxxx'
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
def test_find_elementsFirstview(self):
time.sleep(13)
textfields = self.driver.find_elements_by_class_name("android.widget.EditText")
textfields[0].send_keys("first text")
textfields[1].send_keys("second text")
el = self.driver.find_element_by_name("press Login")
el.click()
def test_secondView(self):
time.sleep(10)
textfields = self.driver.find_elements_by_class_name("android.widget.EditText")
textfields[2].send_keys("secondviewinput2")
def tearDown(self):
# end the session
self.driver.quit()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(SimpleAndroidTests)
unittest.TextTestRunner(verbosity=2).run(suite)
ISSUE is it is not entering to the second view. It is re-loding first view again.
please help...

In your code you have a method - setUp(self) - which nose tools interprets as a "test setup" method, meaning it will be run before each test. Since your setUp() method instantiates the webdriver it is reloading your app before each test. Consider moving your driver instantiation to a setUpClass(), which nose tools will run before all tests in the file.
Example test file:
class YourTest(unittest.TestCase):
#classmethod
def setUpClass(cls):
[...runs before all tests...]
def setUp(self):
[...runs before each test...]
def test_test1(self):
[...your tests...]
def tearDown(self):
[...runs after each test...]
#classmethod
def tearDownClass(cls):
[...runs after all tests...]

When an element on an android app is clicked via appium python script, then appium has no control over the expected behavior. It is the app that handles the click. So for example, if there is a Login button and if you do this:
el = self.driver.find_element_by_name("press Login")
el.click()
This click on the element is handled by the app and app will take over the flow from here. It is app that launches the next screen. For example, it could be a form.
Basically, appium python client has control over which UI element to choose, but what that particular UI element will do is up to the app.

Related

Browser Choice with Automation Test in Python

Initially I have def setup() with options to call specific web browsers from another file that have all the information on how to setup the web browser. Remarking out the browser not used.
def setUp(self):
# Choose the Web Browser to test with
operabrowser(self)
# chromebrowser(self)
...
def test_one()
...
def test_two()
...
I am trying to move away from editing the test file each time, I am looking to setup a console input that will call the browser and I have added to def setup().
browser_choice = input ( """Choose your browser
Opera, [Firefox], Chrome or Safari
> """ ).lower ()
if browser_choice == 'opera':
operabrowser()
else chromebrowser()
This works with a single unit test but if there is more than one test in the file it asks each time for a browser choice.
How can I get this option to be asked only once for all tests that will be ran in the test file? I have tried a few other ways of approaching this all unsuccessful.
Tests should be defined as class methods, in your code they appears to be standalone functions not directly related with the class which holds the setUp() method. You just need to modify your code like this:
import unittest
class YouTests(unittest.TestCase):
def setUp(self):
q = 'Choose your browser Opera, [Firefox], Chrome or Safari >'
browser_choice = input (q).lower ()
if browser_choice == 'opera':
operabrowser()
else:
chromebrowser()
def test_one(self):
pass
def test_two(self):
pass
...
If you have multiple classes inheriting from unittest.TestCase and all should use the same browser the browser choice will be best inserted in your global scope. For example:
browser_object = None
...
def operabrowser():
global browser_object
# Init opera object here
def chromebrowser():
global browser_object
# Init chrome object here
...
# Your tests using the browser_object
...
if __name__ == '__main__':
q = 'Choose your browser Opera, [Firefox], Chrome or Safari >'
browser_choice = input (q).lower ()
if browser_choice == 'opera':
operabrowser()
elif browser_choice == 'firefox':
...
else:
chromebrowser()
unittest.main()

How to pass an url as argument through commandline to run selenium python test cases

Is there any proper way to using getting url in cmd as argument along testcases.py file?
I am running below commmand in cmd to run test cases of python file:
testcases.py "any url"
testcases.py have coding:
class JSAlertCheck(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome("E:\chromedriver.exe")
self.url = sys.argv[1]
def test_Case1(self):
driver = self.driver
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main(sys.argv[1])
As per the discussion Python unittest passing arguments the Python Pundits seems to convey that:
Unit tests should be stand-alone which will have no dependencies outside of their setUp() and tearDown() methods. This is to make sure that each tests has minimal side-effects and reactions to the other test. Passing in a parameter defeats this property of unittest and thus makes them sort of invalid. Using a Test Configuration would have been the easiest way and more appropiate as a unittest should never rely on foreign data to perform the test.
If you still want to do so, here is one of the working solution:
Code Block:
from selenium import webdriver
import unittest
import sys
class MyTest(unittest.TestCase):
URL = "foo"
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver = self.driver
driver.get(self.URL)
def test_Case1(self):
driver = self.driver
print(driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
if len(sys.argv) > 1:
MyTest.URL = sys.argv.pop()
unittest.main()
CLI Command:
python unittest_cmdline_urlASarguments.py http://www.python.org
Output:
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>python unittest_cmdline_urlASarguments.py http://www.python.org
[4448:5632:0606/205445.017:ERROR:install_util.cc(589)] Unable to create registry key HKLM\SOFTWARE\Policies\Google\Chrome for reading result=2
DevTools listening on ws://127.0.0.1:5634/devtools/browser/40cc6c16-1e52-4f49-a54f-08fac3ff7abc
Welcome to Python.org
.
----------------------------------------------------------------------
Ran 1 test in 9.534s
OK
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>
Commandline Snapshot:

In appium, how do i use a test as a dependenciy to another test without running it all the time?

I'm trying to create a few tests in appium, but when i first run the application i have to pass through terms of use screen and first run screens.
Since i only have to run these steps just once, i'm having some hard time to run other tests (when i already ran these screens).
Any ideas of how can i do it?
import os, unittest, time
from appium import webdriver
from time import sleep
class Tests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '0429058934'
desired_caps['app'] = os.path.abspath(os.path.join(os.path.dirname(__file__),'mypath'))
desired_caps['appPackage'] = ''
desired_caps['appActivity'] = '.MainActivity'
desired_caps['fullReset'] = True
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
self.driver.implicitly_wait(30)
def tearDown(self):
self.driver.quit()
def first_run(self):
self.driver.find_element_by_id("p_agreement_btn").click()
next = self.driver.find_element_by_id("next_text")
next.click()
next.click()
next.click()
next.click()
self.driver.find_element_by_id("btn_ok").click()
def test_optimization(self):
self.driver.find_element_by_id("new_powerpro_tab_view_text").click()
self.driver.find_element_by_id("optimization_button").click()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(Tests)
unittest.TextTestRunner(verbosity=2).run(suite)
You are using UnitTest framework for python which is not support dependency like TestNg. if you want to create dependent test then you user Proboscis testing framework, it has same feature like TestNg. Go though above link on read document specially annotations like " #test(depends_on=[UserTests.successful_login])"
For that you can used Proboscis.
Refer link : https://pythonhosted.org/proboscis/

Selenium tests fail after first test

I am trying to run selenium tests I've written for a Django project on a Debian server, using xvfb.
I have 3 tests I am trying to run, after the first test, they fail with this error:
NoSuchElementException: Message: u'Unable to locate element: {"method":"xpath","selector":"//a[#href=\\"#detail\\"]"}'
I have run export DISPLAY=:99 and am using Django LiveServerTestCase with django-selenium.
SELENIUM_DISPLAY = ':99' is set in my settings.py.
Here is my test runner:
class BaseLiveTest(LiveServerTestCase):
#classmethod
def setUpClass(cls):
cls.selenium = WebDriver()
super(BaseLiveTest, cls).setUpClass()
#classmethod
def tearDownClass(cls):
super(BaseLiveTest, cls).tearDownClass()
cls.selenium.quit()
def login(self, user):
#helper function, to log in users
#go to login page
self.selenium.get("%s%s" % (self.live_server_url, reverse('userena_signin')))
#wait for page to display
WebDriverWait(self.selenium, 10).until(
lambda x: self.selenium.find_element_by_id('id_identification'),
)
#fill in form and submit
identifictation_input = self.selenium.find_element_by_id('id_identification')
identifictation_input.send_keys(user.email)
password_input = self.selenium.find_element_by_id("id_password")
password_input.send_keys('password')
self.selenium.find_element_by_xpath('//form/descendant::button[#type="submit"]').click()
#wait for dashboard to load
WebDriverWait(self.selenium, 10).until(
lambda x: self.selenium.find_element_by_id('container'),
)
When I run each test by itself they all pass, but if I try to run them one after another the last 2 fail. Any ideas?
You need to use setUp() and tearDown(), not setUpClass() and tearDownClass(). The Class versions are run globally for the entire fixture, so all 3 tests are using the same WebDriver instance, and thus the browser isn't in the state you expect for your second and third tests.

Selenium Internet Explorer 8 caching issues

when I run my Selenium test on Win XP Internet Explorer 8 , the test doesn't start fresh. It will start the test using the cookies/cache from a previous run. This does not happen when I run the test in Firefox.
Does anyone have a workaround for this? Preferably in Python
Some of my ideas:
- have a script run in the tearDownClass that deletes all temporary files in: C:\Documents and Settings\Owner\Local Settings\Temporary Internet Files
- instead of "*iehta" as the browser I set it to Internet Explorer private mode "*custom C:\Program Files\Internet Explorer\iexplore.exe -private" (--that didn't work due to my syntax being off?
Thank you.
import unittest, inspect, time, re, os
from selenium import selenium
class TESTVerifications(unittest.TestCase):
#classmethod
def setUpClass(self):
self.selenium = selenium("localhost", 4444, "*iehta", "https://workflowy.com/")
self.selenium.start()
self.selenium.set_timeout("60000")
print("setUpClass")
self.selenium.window_maximize()
self.selenium.open("/")
def setUp(self):
self.verificationErrors = []
def test_login_6(self):
sel = self.selenium
sel.open("/")
sel.type("css=input[id='id_username']",'test+abc010#workflowy.com' )
sel.type("css=input[id='id_password']",'password')
sel.click("css=form[id='login'] > input.submit")
sel.wait_for_page_to_load("60000")
self.failUnless(sel.is_element_present("id=logout"))
def tearDown(self):
#self.selenium.stop()
self.assertEqual([], self.verificationErrors,"Results: " + str(self.verificationErrors))
#classmethod
def tearDownClass(self):
self.selenium.stop()
print("tearDownClass")
if __name__ == "__main__":
unittest.main()
You can use sel.delete_all_visible_cookies() which will remove any cookie created by the current domain. If you have multiple domains, you can use the following:
def clean_history(sel, domains):
temp = sel.get_location()
for domain in domains:
sel.open(domain)
sel.delete_all_visible_cookies()
sel.open(temp)
See this blog post for more information.

Categories