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.
Related
I am trying to run Selenium test in Python on Linux Ubuntu environment.
Geckodriver is located in my project root folder.
I run the file named siteTest.py from PyCharm command line:
python3 siteTest.py
However, I do not see any output from Selenium.
The test worked before I divided it into setUp, test and tearDown and added self as a parameter.
Any suggestions what I am doing wrong?
Thanks in advance.
import os
import unittest
from selenium import webdriver
class siteTest:
def setUp(self):
ROOT_DIR = os.path.abspath(os.curdir)
self.driver = webdriver.Firefox(executable_path=ROOT_DIR + '/geckodriver')
def test(self):
driver = self.driver
driver.get('https://google.com/')
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
Your program was near perfect. You just need to annotate the siteTest class as unittest.TestCase. So effectively, you need to rewrite the line:
class siteTest:
as:
class siteTest(unittest.TestCase):
You probably need to annotate your set up and tear down methods.
#classmethod
def setUp(self)
.
.
#classmethod
def tearDown(self)
.
.
Here, I have annotated as class method so it will run only once for the class.
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:
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/
I have a little issue with webdriver.My machine run windows 7 and successfuly install python and selenium webdriver.Here is the problem
When i run this file
from selenium import webdriver
import HTMLTestRunner
import unittest
class nexmo(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.get("http://wwww.facebook.com")
def test_login(self):
emailFieldId = "email"
el = self.driver.find_element_by_id(emailFieldId)
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
The test give me
Ran 0
OK But the Firefox doesnt start and do the things i tell him.
When I run
from selenium import webdriver
self.driver = webdriver.Firefox()
self.driver.get("http://wwww.facebook.com")
emailFieldId = "email"
el = self.driver.find_element_by_id(emailFieldId)
self.driver.quit()
Everything is OK.The browser starts and find the element.
I took your code and copy/pasted it into my Eclipse and it ran fine.
By chance did you re-type this code into SO rather than copy paste? Is it possible that there is a typo in your "def test_login(self):" line such that unittest can't identify it as a test case? This is my best guess. Since unittest first checks to see if you have any unit tests (identified as a function with the pre-fix "test_". If and only if it finds a test case will it run setUp and tearDown.
Also, the point of unit testing is to actually test that you received a valid value. Can I recommend adding this to the end of "def test_login":
self.assertIsNotNone(el)
I am working on Win7 with PyCharm3. I have a functional test 'y1.py' which I have exported from the selenium IDE. It contains:
class Y1(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://www.yahoo.com/"
self.verificationErrors = []
self.accept_next_alert = True
def test_y1(self):
driver = self.driver
driver.get(self.base_url)
driver.find_element_by_link_text("Weather").click()
driver.get_screenshot_as_file('foo.png')
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
When I run the script from the pycharm manage.py tool I realized that the screenshots are being saved to
PyCharm 3.0.1\jre\jre\bin"
Also, for some reason specifying the path explicitly does not work :
(driver.get_screenshot_as_file('c/foo1.png') ).
I've tried variations of this based on Webdriver Screenshot, but can't get it to work. How could I use python to directly save the screenshot to a directory "screenshots" under my project root?
Edit:
I realized that there is a difference b/w the command line's manage.py and pycharm's tools->manage.py ( which is what I've been using ). When you run it from the command line the tests run much faster and the screenshot saves in the project's root directory ( which is what I wanted ). Hope this helps someone. - Bill
I didn't have success with get_screenshot_as_file() but I offer an alternative using get_screenshot_as_base64(). Define this function in another module:
def save_screenshot(self, driver, file_name_prefix):
img_str64 = driver.get_screenshot_as_base64()
f = open("screenshots/%s.png" % file_name_prefix, "wb")
f.write(img_str64.decode("base64"))
f.close()
Then, in the test replace
driver.get_screenshot_as_file('foo.png')
module_containing_this_function.save_screenshot("foo")