How to input parameters into Selenium RC TestSuite? - python

I have to test few sites which sales the same things, but they have an another template.
So I want to run each MainTestClass with giving some input parameter, let's say :
java -jar SeleniumServerStandalone-2.0b2.jar -port 5555 (template_id=5)
Is it possible?
class MainTestCases(unittest.TestCase):
def setUp(self):
#self.template_id=template_id I want something like that
self.verificationErrors = []
self.selenium = selenium("localhost", 5555, "*chrome", "http://www.google.com/")
time.sleep(5)
self.selenium.start()
def test_test1(self):
if self.template_id==1:
...
elif self.template_id==2:
...
def test_test2(self):
if self.template_id==1:
...
elif self.template_id==2:
...
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()

Try adding an init method to MainTestCases, like so:
class MainTestCases(unittest.TestCase):
def __init__(self, methodName, template_id):
super(MainTestCases, self).__init__(self, methodName)
self.template_id = templateId
def setUp(self):
... and so on...
Due to this customization, you will need to build your test suite manually because each test case has to be instantiated with the template_id, like so--
def suite(template_id):
testcasenames = unittest.defaultTestLoader.loadTestsFromTestCase(MainTestCases)
suite = []
for case in testcasename:
suite.append(MainTestCases(case, template_id)
return suite
Then in main, instead of unittest.main(), do:
Parse command-line arguments. You may want to consider the argparse (2.7+) or optparse (2.6 and earlier) modules. They are powerful, but easy to start with by looking at the examples.
Create and run the suite: unittest.TextTestRunner().run(suite(template_id))

Now, I use this solution:
Create suite test which runs testcases:
import unittest
from Flights.FlightsTestCases import FlightsTestCases
import sys
from Flights.FlightTemplate import FlightTemplate
def suite():
testSuite= unittest.TestSuite()
testSuite.addTest(FlightsTestCases('test_test1'))
FlightsTestCases.www_address='http://testpage.pl/'
FlightsTestCases.flight_template=FlightTemplate.Test
#FlightsTestCases.www_address='http://productionpage.pl/'
#FlightsTestCases.flight_template=FlightTemplate.Production
return testSuite
if __name__ == "__main__":
result = unittest.TextTestRunner(verbosity=2).run(suite())
sys.exit(not result.wasSuccessful())
change set_up to something like:
class FlightsTestCases(unittest.TestCase):
www_address = None
flight_template = None
xml_report_generator = None
def setUp(self):
self.verificationErrors = []
if self.www_address == None:
self.selenium = selenium("localhost", 5555, "*chrome", "http://testpage.pl/")
else:
self.selenium = selenium("localhost", 5555, "*chrome", self.www_address)

Related

Falcon, wsgiref : Unit test cases

I have the below code:
master.py
def create():
master = falcon.API(middleware=Auth())
msg = Message()
master.add_route('/message', msg)
master = create()
if __name__ == '__main__':
httpd = simple_server.make_server("127.0.0.1", 8989, master)
process = Thread(target=httpd.serve_forever, name="master_process")
process.start()
#Some logic happens here
s_process = Thread(target=httpd.shutdown(), name="shut_process")
s_process.start()
s.join()
I tried to create the below test case for the below:
from falcon import testing
from master import create
#pytest.fixture(scope='module')
def client():
return testing.TestClient(create())
def test_post_message(client):
result = client.simulate_post('/message', headers={'token': "ubxuybcwe"}, body='{"message": "I'm here!"}') --> This line throws the error
assert result.status_code == 200
I tried running the above but get the below error:
TypeError: 'NoneType' object is not callable
I actually am unable to figure out how I should go about writing the test case for this.
Based on what #hoefling said, the below fixed it:
master.py
def create():
master = falcon.API(middleware=Auth())
msg = Message()
master.add_route('/message', msg)
return master
master = create()
if __name__ == '__main__':
httpd = simple_server.make_server("127.0.0.1", 8989, master)
process = Thread(target=httpd.serve_forever, name="master_process")
process.start()
#Some logic happens here
s_process = Thread(target=httpd.shutdown(), name="shut_process")
s_process.start()
s.join()
And then the test case works:
from falcon import testing
from master import create
#pytest.fixture(scope='module')
def client():
return testing.TestClient(create())
def test_post_message(client):
result = client.simulate_post('/message', headers={'token': "ubxuybcwe"},
body='{"message": "I'm here!"}')
assert result.status_code == 200
Thanks a lot #hoefling!

sortTestMethodsUsing doesn't work correctly

I try to order my tests but the problem is that the test_add will be first and I need that the test_remove will be first. I try to use sortTestMethodsUsing but I still get test_add as the first test.
import unittest
class TestSum(unittest.TestCase):
def test_remove(self):
print("1")
def test_add(self):
print("2")
if __name__ == '__main__':
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = None
unittest.main(testLoader=loader)

An element could not be located on the page using the given search parameters

Appium automation runs and ends correctly inside one class, but fails when another class is created.
I tried to to delete all attributes in init, except first one and it helps.
Main Class(works well)
import unittest
from appium import webdriver
from ScreenObjects.SendMessage import SendMsg
class AppTestAppium(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = ''
desired_caps['deviceName'] = '81e9b20e'
desired_caps['appPackage'] = 'org.telegram.messenger'
desired_caps['appActivity'] = 'org.telegram.ui.LaunchActivity'
desired_caps['noReset'] = 'True'
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)
def tearDown(self):
"Tear down the test"
self.driver.quit()
def test_send_messge_to_olga(self):
"Test is sending message"
contactItem = self.driver.find_element_by_xpath("//android.view.ViewGroup[contains(#index,'2')]")
contactItem.click()
elementTypeField = self.driver.find_element_by_xpath("//android.widget.EditText[contains(#index,'1')]")
elementTypeField.clear()
elementTypeField.send_keys("Hello. If you are reading this, my first appium automation has passed")
sendButton = self.driver.find_element_by_xpath("//android.widget.ImageView[#content-desc ='Send']")
sendButton.click()
if __name__ == '__main__':
unittest.main()
Main class(fails)
import unittest
from appium import webdriver
from ScreenObjects.SendMessage import SendMsg
class AppTestAppium(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = ''
desired_caps['deviceName'] = '81e9b20e'
desired_caps['appPackage'] = 'org.telegram.messenger'
desired_caps['appActivity'] = 'org.telegram.ui.LaunchActivity'
desired_caps['noReset'] = 'True'
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_caps)
def tearDown(self):
"Tear down the test"
self.driver.quit()
def test_send_messge_to_olga(self):
"Test is sending message"
send_message = SendMsg(self.driver)
send_message.chooseContact()
send_message.typeMsg()
send_message.clickSend()
if __name__ == '__main__':
unittest.main()
with one more Class (fails)
class SendMsg(object):
def __init__(self, driver):
self.contactItem = driver.find_element_by_xpath("//android.view.ViewGroup[contains(#index,'2')]")
self.elementTypeField = driver.find_element_by_xpath("//android.widget.EditText[contains(#index,'1')]")
self.sendButton = driver.find_element_by_xpath("//android.widget.ImageView[#content-desc ='Send']")
def chooseContact(self):
self.contactItem.click()
def typeMsg(self):
self.elementTypeField.clear()
self.elementTypeField.send_keys("Hello")
def clickSend(self):
self.sendButton.click()
I expect TEST PASSED, but the actual output is 'An element could not be located on the page using the given search parameters.'

click python Cli.testing TypeError

I have 2 files:
click_example.py
import click
#click.group(invoke_without_command=True)
#click.option('--apikey', default='My key',
help="API key to use.")
#click.pass_context
def main(ctx, apikey):
"""
A CLI for live and past football scores from various football leagues.
resources are given as commands and subresources and their filters as options
"""
headers = {'X-Auth-Token': apikey}
ctx.obj['headers'] = headers
#main.command()
#click.option('--limit', '-l', help='limit number of records')
def scorers(limit):
click.echo('limit is : %s' % limit)
if __name__ == '__main__':
main(obj={})
and a test file:
test_cs.py
from click.testing import CliRunner
import unittest
from .clicksample import main
class Sample(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
def tearDown(self):
pass
def test_sample_command(self):
result = self.runner.invoke(main)
self.assertEqual(0, result.exit_code)
if __name__ == '__main__':
unittest.main()
I want to know why the test does not pass. When I run the clicksample script from the command line it works as expected but for some reason it does not exit as expected in the test. When I poke the result using pdb I get the following stats:
(Pdb) result
<Result TypeError("'NoneType' object does not support item assignment",)>
(Pdb) result.exit_code
-1
(Pdb)
You never set ctx.obj. This can fix that for you:
def main(ctx, apikey):
if ctx.obj is None:
ctx.obj = {}
...

Using arg parser in python in another class

I'm trying to write a test in Selenium using python,
I managed to run the test and it passed, But now I want add arg parser so I can give the test a different URL as an argument.
The thing is that my test is inside a class,
So when I'm passing the argument I get an error:
app_url= (args['base_url'])
NameError: global name 'args' is not defined
How can I get args to be defined inside the Selenium class?
This is my code:
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium import webdriver
import unittest, time, re
import os
import string
import random
import argparse
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
agmuser = id_generator()
class Selenium(unittest.TestCase):
def setUp(self):
chromedriver = "c:\chromedriver.exe"
os.environ["webdriver.chrome.driver"] = chromedriver
self.driver = webdriver.Chrome(chromedriver)
app_url = (args['base_url'])
#app_url= "http://myd-vm16635.fufu.net:8080/"
print "this is the APP URL:" + ' ' + app_url
self.base_url = app_url
self.verificationErrors = []
self.accept_next_alert = True
def test_selenium(self):
#id_generator.user = id_generator()
driver = self.driver
driver.get(self.base_url + "portal/")
driver.find_element_by_css_selector("span").click()
driver.find_element_by_id("j_loginName").clear()
driver.find_element_by_id("j_loginName").send_keys(agmuser)
driver.find_element_by_id("btnSubmit").click()
driver.find_element_by_link_text("Login as" + ' ' + agmuser).click()
driver.find_element_by_css_selector("#mock-portal-Horizon > span").click()
# driver.find_element_by_id("gwt-debug-new-features-cancel-button").click()
# driver.find_element_by_xpath("//table[#id='gwt-debug-module-dropdown']/tbody/tr[2]/td[2]").click()
# driver.find_element_by_id("gwt-debug-menu-item-release-management").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException as e: return False
return True
def is_alert_present(self):
try: self.driver.switch_to_alert()
except NoAlertPresentException as e: return False
return True
def close_alert_and_get_its_text(self):
try:
alert = self.driver.switch_to_alert()
alert_text = alert.text
if self.accept_next_alert:
alert.accept()
else:
alert.dismiss()
return alert_text
finally: self.accept_next_alert = True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
#####################******SCRIPT PARAMS****;**###################################
# these values can be changed type 'python selenium_job.py --help' for assistance
##################################################################################
parser = argparse.ArgumentParser(description='DevOps team - Sanity test')
parser.add_argument('-b', '--base_url', help='base_url', default="http://myd-vm16635.fufu.net:8080/")
args = vars(parser.parse_args())
unittest.main()
Put the parser = argparse.ArgumentParser(...) and parser.add_argument() outside if __name__ == "__main__": so that it always gets created but not evaluated. Keep args = vars(parser.parse_args()) inside __main__.
That way you can import it from the file like from selenium_tests import parser and then in your other script, do parser.parse_args().
And a cleaner way to do it is to create a function which returns the parser, like:
def get_parsed_args():
parser = argparse.ArgumentParser(...)
parser.add_argument(...)
# etc.
args = parser.parse_args()
return args
# or just...
return parser.parse_args()
#and then call that in the main program:
if __name__ == '__main__':
args = get_parsed_args()
# etc.
And in other scripts which you want to import it into, do
from selenium_tests import get_parsed_args
if __name__ == '__main__':
args = get_parsed_args()
# etc.

Categories