Django test using Selenium package error - python

I want to create some Django test using Selenium package.
Here below is the simple test :
import unittest
from selenium import webdriver
class TestSignup(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_signup_fire(self):
self.driver.get("http://localhost:8000/add/")
self.driver.find_element_by_id('id_title').send_keys("test title")
self.driver.find_element_by_id('id_body').send_keys("test body")
self.driver.find_element_by_id('submit').click()
self.assertIn("http://localhost:8000/", self.driver.current_url)
def tearDown(self):
self.driver.quit
if __name__ == '__main__':
unittest.main()
but I take this error :
TypeError: environment can only contain strings
in this line :
self.driver = webdriver.Firefox()
and I don't know why, any idea how to fix this error?

As you are seeing the error as :
TypeError: environment can only contain strings
In the line :
self.driver = webdriver.Firefox()
This essentially means there is some configuration error while updating the path within Environment Variables. To suppress that you can supply the argument with geckodriver binary location as follows :
self.driver = webdriver.Firefox(executable_path=r'C:\path\to\geckodriver.exe')

Related

Implicitly_wait() missing 1 required positional argument

I'm studying selenium with python and in a tutorial I found the following code.
from selenium import webdriver
from time import gmtime, strftime
import unittest
#from builtins import classmethod
class RegisterNewUser(unittest.TestCase):
##classmethod
def setUp(self):
self.driver = webdriver.Firefox
self.driver.implicitly_wait(30)
self.driver.maximize_window()
# navigate to the application home page
self.driver.get("http://demo-store.seleniumacademy.com/")
def test_register_new_user(self):
driver = self.driver
pass
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main(verbosity=2)
It throw an error:
File "register_new_user.py", line 10, in setUp
self.driver.implicitly_wait(30)
TypeError: implicitly_wait() missing 1 required positional argument: 'time_to_wait'
I try to add the code commented out (classmethod) but doesn't change anything. Without the test_register_new_user doesn't give error.
I'm using python 3.6.4, selenium 3.141 (and geckodriver 0.23)
Your problem is one line above:
self.driver = webdriver.Firefox
This does not create a browser object. It just sets self.driver to the class webdriver.Firefox, which means that self.driver.implicitly_wait(30) is trying to use implicitly_wait in the static way, ie webdriver.Firefox.implicitly_wait(30), so it is missing the instance, ie webdriver.Firefox.implicitly_wait(an_actual_browser, 30).
You are missing ():
self.driver = webdriver.Firefox() # which will potentially ask for a path to
# firefox/geckodriver if it is not in PATH,
# but that is out of the scope of this question

ran 0 tests in 0.000s - while executing Python-unittest with Selenium

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class loginAvaliador(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('/Users/r13/dev/chromedriver')
def login_avaliador(self):
driver = self.driver
driver.get("http://d3dyod5mwyu6xk.cloudfront.net/")
assert "FGV" in driver.title
cpf = driver.find_element_by_xpath('//input[#placeholder="CPF"]')
cpf.send_keys("27922797885")
password = driver.find_element_by_xpath('//input[#placeholder="SENHA"]')
password.send_keys("enccejaregular")
login = driver.find_element_by_tag_name('button')
login.click()
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
when i try to run this test script it returns "ran 0 tests in 0.000s" why this is happening? i'm new to python and writting this test scripts so i can't find the error
With the unittest module, you need to use their built in assertion methods. Instead of just writing
assert a not in b
you write
self.assertNotIn("No results found.",driver.page_source)
for example. For a list of all the assert methods look here:
https://docs.python.org/2/library/unittest.html#unittest.TestCase
While working through Python's unittest module with Selenium you have to consider a few facts as follows :
You need to take care of the indents. Indentation for class and test_method are different.
While you define the #Tests name the tests starting with test e.g.
def test_login_avaliador(self):
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.
Here is your own code with the required minor modifications :
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class loginAvaliador(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\WebDrivers\chromedriver.exe')
def test_login_avaliador(self):
driver = self.driver
driver.get("http://d3dyod5mwyu6xk.cloudfront.net/")
assert "FGV" in driver.title
cpf = driver.find_element_by_xpath('//input[#placeholder="CPF"]')
cpf.send_keys("27922797885")
password = driver.find_element_by_xpath('//input[#placeholder="SENHA"]')
password.send_keys("enccejaregular")
login = driver.find_element_by_tag_name('button')
login.click()
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
Execution Result:
C:\path\to\PyPrograms>python -m unittest 52560471_unittest.py
DevTools listening on ws://127.0.0.1:12022/devtools/browser/078fc4e9-3ca6-4bbb-b318-0b8f04318d32
.
----------------------------------------------------------------------
Ran 1 test in 40.796s
OK

Defining the path to a module in Windows (Where the module is the test file being run)

I'm trying to run a simple automated test script. My code looks like:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
gecko = os.path.normpath(os.path.join(os.path.dirname(__file__), 'geckodriver'))
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path=gecko+'.exe')
class PythonOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = driver
def test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.python.org")
self.assertIn("Python", driver.title)
elem = driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
When I run it, I get the error:
Error while finding module specification for 'test_file.py' (AttributeError: module 'test_file' has no attribute 'path')
I have been searching all over stack overflow for how to resolve this or define a path. I am new to Windows operating systems and unit testing so I'm very lost on how to resolve this. If you have any insight, it would be much appreciated.

Error while switching window in python selenium

I want to work with multiple windows and tabs using selenium and python.
I am getting below error during script execution:-
( code is mentioned at last)
{f625f26d-cfcf-442c-b9fc-5e96a199cd43}
C:\Python34\lib\site-packages\selenium-2.47.1- py3.4.egg\selenium\webdriver\remot
e\webdriver.py:525: DeprecationWarning: use driver.switch_to.window instead
warnings.warn("use driver.switch_to.window instead", DeprecationWarning)
{cad6e3cf-9062-408e-a6f1-11e98813dc6c}
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
class GoogleTabs(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print (window_before)
driver.find_element_by_xpath("//a[#href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
print (window_after)
driver.find_element_by_link_text("ATM").click()
driver.switch_to_window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
As the warning says
DeprecationWarning: use driver.switch_to.window instead
you'll need to change your
driver.switch_to_window
with
driver.switch_to.window
But think about it: it is a warning, not an error! Your code should work, it is just telling you that that method is deprecated.
You're getting a warning message, for new versions of selenium the method has changed.
Instead of using: driver.switch_to_window(window)
Try with: driver.switch_to.window
Where window is your variable.
I propose a very simple way to switch between windows without any hassles of playing with the handles yourself. https://gist.github.com/ab9-er/08c3ce7d2d5cdfa94bc7
def change_window(browser):
"""
Simple window switcher without the need of playing with ids.
#param browser: Current browser instance
"""
curr = browser.current_window_handle
all_handles = browser.window_handles
for handle in list(set([curr]) - set(all_handles)):
return browser.switch_to_window(handle)

Python WebDriver AttributeError: LoginPage instance has no attribute 'driver'

I have read a few tutorials on Python Selenium Webdriver Page Object model as I have to automate the gui tests using Selenium with Python.
To start off with I am trying to write a Login Page class and a LoginMainTest class. I am getting the following error when i run the code.
AttributeError: LoginPage instance has no attribute 'driver'
I think i have to specify the selenium driver where i instantiate the LoginPage
e.g. on this line log_in = LoginPage.LoginPage()
I need some help please.
Full error:
Traceback (most recent call last):
File "E:\Python projects\unitTest_sample - Modifying into Page Object\LoginMainTest.py", line 11, in test_valid_login
log_in = LoginPage.LoginPage()
File "E:\unitTest_sample - Modifying into Page Object\LoginPage.py", line 20, in __init__
emailFieldElement = self.driver.find_element_by_id(self.emailFieldID)
AttributeError: LoginPage instance has no attribute 'driver'
My LoginMainTest.py class is as follows:
import LoginPage
import unittest
class GoogleTest(unittest.TestCase):
def test_valid_login(self):
log_in = LoginPage.LoginPage()
log_in.userLogin_valid()
if __name__ == '__main__':
unittest.main()
My Login.py class is as follows:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
class LoginPage():
Username = "test1"
password = "Test"
emailFieldID = "email"
passFieldID = "pass"
loginButtonXpath = "//input[#value='log in']"
logo_xpath = "//a[contains(#href, 'logo')])[1]"
def setup(self):
self.driver = webdriver.Firefox()
self.driver.get("http://www.testaaa.com")
def __init__(self):
emailFieldElement = self.driver.find_element_by_id(self.emailFieldID)
passFieldElement = self.driver. find_element_by_id(self.passFieldID)
loginFieldElement = self.driver.find_element_by_xpath(self.loginButtonXpath)
def userLogin_valid(self):
self.emailFieldElement.clear()
self.emailFieldElement.send_keys(self.Username)
self.passFieldElement.clear()
self.send_keys(self.password)
self.loginFieldElement.click()
def tearDown(self):
self.driver.quit()
Firstly, there is a flaw in your design.
The reason your script is failing because when you create the object of login page the init gets called but it fails to find the driver since it is defined in the setup fn (which is never called)
Ideally in the page object model you should initialize your browser(driver) in your test file and then while creating a object of any page file you should pass that driver.
Your setup should look something like this,
Page file:
# setup() fn not needed here
.
.
def __init__(self, driver):
self.driver = driver
emailFieldElement = self.driver.find_element_by_id(self.emailFieldID)
passFieldElement = self.driver. find_element_by_id(self.passFieldID)
loginFieldElement = self.driver.find_element_by_xpath(self.loginButtonXpath)
.
# teardown() not needed here, should be in test file
.
Test File:
.
.
class GoogleTest(unittest.TestCase):
def test_valid_login(self):
self.driver = webdriver.Firefox() # the first 2 stmts can be in a setupclass
self.driver.get("http://www.testaaa.com")
log_in = LoginPage.LoginPage(self.driver)
log_in.userLogin_valid()
.
.
I've had this issue a couple of times and every time I found it due to a mismatch between my Chrome browser version and the Chrome Webdriver version.
So, in your Chrome browser check Help>About Google Chrome before downloading a corresponding ChromeDriver from https://chromedriver.chromium.org/.
Good luck!

Categories