How to to run unitest and selenium from a django view? - python

I have a functional test 'y1.py' which I have exported from the selenium IDE. It looks like:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
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.save_screenshot('out11.png')
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()
I am trying to call this directly from within a python/django function. while investigating this I came across: AttributeError 'module' object has no attribute 'runserver' in django, where Udi states:
Are you trying to run unitest and selenium from a view? You should
consider launching a second process for that.
How can I do this?

You can start django server as new process with subprocess module.

Related

python selenium inherit webdriver methods

I've been looking for a solution to inherit the methods of the python selenium webdriver class so that I can extend/modify its behaviour. I have not found one that work.
For instance, I want to inherit all the methods of the chrome webdriver but extend the .get() method (i.e. the method to load a url). This is my current approach:
from selenium import webdriver
from selenium.common.exception import TimeoutException
class CustomDriver:
def __init__(self, browser):
if browser.lower() == 'chrome'
self.driver = webdriver.Chrome()
def get_url(self, url):
try:
self.driver.get(url)
except TimeoutException:
self.driver.quit()
This methods works but it does not inherit the general webdriver methods like driver.quit(). In fact, if I do the following:
mydriver = CustomDriver('Chrome')
mydriver.quit()
I get the error: 'Custom driver' object has no attribute quit.
Has any of you any suggestions?
ps: I'm new to python.
quit() is from webdriver methods and you are importing it from selenium module, and you have created a object self.driver for the webdriver.Chrome()
so you can't use webdriver method on created class object that is the reason why you are getting No Attribute Error : 'Custom driver' object has no attribute quit
One way of obtaining inheritance is by declaring respective method inside the class and inherit those methods outside.
Refer this document: https://www.geeksforgeeks.org/web-driver-methods-in-selenium-python/
Below is the code that would work
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
class CustomDriver:
def __init__(self, browser):
if browser.lower() == 'chrome':
self.driver = webdriver.Chrome()
def exit_browser(self):
self.driver.quit()
def get_url(self, url):
try:
self.driver.get(url)
except TimeoutException:
self.driver.quit()
mydriver = CustomDriver('Chrome')
mydriver.get_url("https://www.google.com/")
mydriver.exit_browser()

Selecting checkboxes using selenium web driver with python

I am trying to perform a test on Amazon.com categories checkboxes using selenium web driver with python code, and I tried several ways but I am not sure how to select the checkbox of the Book category for example without having its id or name. I used some plugins to get the right xpath like XPath Helper for chrome and path checker on Firefox...
Here is my code and my tries are commented.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[#name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[#name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
HTML
<span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{"attribute":"whitelist_categories","value":"283155","rangeEnd":"","rangeStart":"","filterType":"checkboxes"}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
I have solved my problem with a very simple line of code using the right xpath:
self.browser.find_element_by_xpath("(//input[#name=''])[8]").click()
and it perfectly worked!
I have modified your code and now it's working
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
sleep(5)
self.browser.find_element_by_xpath("//span[#class='a-label a-checkbox-label' and contains(text(),'Books')]/preceding-sibling::input[1]").click()
self.browser.close()
if __name__ == "__main__":
unittest.main(verbosity=2)

Selenium Python: What are the errors in my code?

i would like to know why this code opens mozilla twice, and why it doesn´t close it when finishes. Furthermore, i don´t understand 100% why login is a class with a function, and not a function directly.
> import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self):
self.driver = webdriver.Firefox()
def logindetails(self, username, password):
driver = self.driver
driver.maximize_window()
driver.get("https://miclaro.claro.com.ar/")
driver.implicitly_wait(30)
driver.find_element_by_id("_58_login_movil").send_keys(username)
driver.find_element_by_id("_58_password_movil").send_keys(password)
driver.find_element_by_id("btn-home-login").click()
# Login Success
class TestLogin(unittest.TestCase):
def setUp(self):
self.ld = LoginDetails()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
Thank you very much!
This is because you instantiate webdriver twice - once inside the TestCase and once inside the LoginDetails class.
Why the other answer is not entirely correct
The WebDriver should not be controlled by the LoginDetails class in this case. LoginDetails class is very close to a Page Object notation representation and, hence, should be given the driver "from outside". Plus, opening browser in one class and closing it in the other is making the code close to "Spaghetti".
Better solution
Control the webdriver from the TestCase class and "share" with the LoginDetails:
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self, driver):
self.driver = driver
def logindetails(self, username, password):
driver = self.driver
driver.maximize_window()
driver.get("https://miclaro.claro.com.ar/")
driver.implicitly_wait(30)
driver.find_element_by_id("_58_login_movil").send_keys(username)
driver.find_element_by_id("_58_password_movil").send_keys(password)
driver.find_element_by_id("btn-home-login").click()
class TestLogin(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.ld = LoginDetails(self.driver)
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
self.driver.close()
Firefox opens twice
In your test self.ld = LoginDetails() runs the __init__ function of LoginDetails() which in turn runs webdriver.Firefox() then you issue the same in the next line in the test case. That is why Firefox opens twice.
Firefox does not close
For the same reason as above Firefox is not closed. The tearDown of your test case only closes the instance of webdriver.Firefox() defined in the test case itself not the one opened via the __init__ function of the class.
Why LoginDetails is a class
LoginDetails is a class in this case to keep webdriver.Firefox() persistent throughout your code. If it would be a function you would open one Firefox session each time you run the function. Unless you specify webdriver.Firefox() outside the function and then pass it to the function.
Corrected Code
The following code uses the class functionality:
import unittest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class LoginDetails(object):
def __init__ (self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
def logindetails(self, username, password):
self.driver.maximize_window()
self.driver.get("https://miclaro.claro.com.ar/")
self.driver.implicitly_wait(30)
self.driver.find_element_by_id("_58_login_movil").send_keys(username)
self.driver.find_element_by_id("_58_password_movil").send_keys(password)
self.driver.find_element_by_id("btn-home-login").click()
def __del__(self):
''' ADDED based on comment by alecxe '''
self.driver.close()
class TestLogin(unittest.TestCase):
def setUp(self):
self.ld = LoginDetails()
def test_sr_Login(self):
self.ld.logindetails("user", "pass")
def tearDown(self):
# driver is closed by LoginDetails
pass
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()

How do i run more than 1 Test Case in Python Webdriver. Only 1 of my test case class runs

In my automation page object model script I have created 2 TestCases so far with some test cases, methods.
class LoginPage_TestCase(unittest.TestCase):
class AdministrationPage_TestCase(unittest.TestCase):
LoginPage has a test for testing a valid user login
AdministrationPage has 1 method so far add_Project (user can add a project after having logged in)
In the PyCharm editor I have AdministrationPage open. I click the green run icon to run the test case. I want to see if my method add_project works before i continue writing more methods.
When the test runs it runs the LoginPage Test Case and then it stops there.
How can i run the AdministrationPage Test Case?
Also If i wanted to run LoginPage Test Case first and then AdministrationPage to run when LoginPage has completed. How can i do this?
Thanks!
My code is snippet for LoginPage and AdministraionPage is as follows:
LoginPage_TestCase.py
from selenium import webdriver
from Pages import page
from Locators import locators
from Locators import element
class LoginPage_TestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Ie("C:\QA\Automation\Python_projects\Selenium Webdriver\IEDriverServer_Win32_2.45.0\IEDriverServer.exe")
self.driver.get("http://riaz-pc.company.local:8080/clearcore")
self.login_page = page.LoginPage(self.driver)
self.driver.implicitly_wait(30)
def test_login_valid_user(self):
print "test_login_valid_user"
login_page = page.LoginPage(self.driver)
login_page.userLogin_valid()
login_page.isAdministration_present()
print login_page.isAdministration_present()
assert login_page.isAdministration_present(), "Administration link not found"
def test_login_invalid_user(self):
print "test_login_invalid_user"
#login_page = page.login(self.driver)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
AdministrationPage_TestCase.py
import unittest
import time
from selenium import webdriver
from locators import locators
from locators import element
from Pages import page
from Pages.administrationPage import AdministrationPage
from Pages.page import LoginPage
class AdministrationPage_TestCase(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Ie("C:\QA\Automation\Python_projects\Selenium Webdriver\IEDriverServer_Win32_2.45.0\IEDriverServer.exe")
self.driver.get("http://riaz-pc.company.local:8080/clearcore")
self.login_page = page.LoginPage(self.driver)
print "I am here in setUp self.login_page = page.LoginPage(self.driver)"
self.driver.implicitly_wait(30)
def add_Project(self):
login_page = page.LoginPage(self.driver)
login_page.userLogin_valid()
administration_page = login_page.clickAdministration(self.driver)
administration_page.AdministrationPage.add_project()
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
AdministrationPage.py
from selenium.common.exceptions import NoSuchElementException
from Locators.locators import MainPageLocators
from Locators import locators
from Locators import element
from Locators.element import BasePageElement
class BasePage(object):
def __init__(self, driver):
self.driver = driver
class AdministrationPage(BasePage):
# Add a project, enter project name & description, save
def add_project(self):
add_project_button = self.driver.find_element(*MainPageLocators.addButton_project)
add_project_button.click()
project_name_textfield = self.driver.find_element(*MainPageLocators.projectName_textfield)
project_name_textfield.click()
project_name_textfield.clear()
project_name_textfield.sendkeys('LADEMO_IE_nn_')
project_description_textfield = self.driver.find_element(*MainPageLocators.projectDescription_textfield)
project_description_textfield.click()
project_description_textfield.clear()
project_name_textfield.sendkeys("LADEMO create a basic project test script - Selenium Webdriver/Python Automated test")
1) Your test methods should start with test_.
2) You should configure pycharm as:

Auto Filling Forms That Use ASP

I am trying to write some code, to automatically fill this webform:
http://scoweb.sco.ca.gov/UCP/
Then read the returned results. I'll look for my name and notify myself when I have UCP.
I have tried writing programs in C#(System.Net), curl(in conjunction with formfind), Ruby(Mechanize), and Python(Scrapy, urllib2).
All of my scripts work on regular HTML forms that communicate with databases, but this one returns nothing.
My theory is because the site uses ASP and I am failing to do something to account for that?
Any working code, though python preferred, filling the form and returning the results would be greatly appreciated.
I think the problem is because the form uses javascript. You can use selenium for such a thing http://seleniumhq.org/
#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import unittest, time, re
class Shiply(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "http://scoweb.sco.ca.gov/" #California UCP
self.verificationErrors = []
def test_shiply(self):
driver = self.driver
driver.get(self.base_url + "/UCP/")
driver.find_element_by_id("ctl00_ContentPlaceHolder1_txtLastName").clear()
driver.find_element_by_id("ctl00_ContentPlaceHolder1_txtLastName").send_keys("YOUR_NAME")
driver.find_element_by_id("ctl00_ContentPlaceHolder1_btnSearch").click()
def is_element_present(self, how, what):
try: self.driver.find_element(by=how, value=what)
except NoSuchElementException, e: return False
return True
def tearDown(self):
self.driver.quit()
self.assertEqual([], self.verificationErrors)
if __name__ == "__main__":
unittest.main()

Categories