I'm beginner in Appium automation,I trying sent messages but have some errors,hope someone help me.
I use "send_keys("0911111111")" it just print into the textbox but can't search and it didn't have search button.
https://imgur.com/a/jo3T0hA
import unittest
from appium import webdriver
from time import sleep
from appium.webdriver.common.touch_action import TouchAction
# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
class ContactsAndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
#desired_caps['automationName'] = 'UiAutomator1'
desired_caps['platformVersion'] = '10.0'
desired_caps['udid'] = '8BLAY00DSD'
desired_caps['deviceName'] = 'Pixel 3a'
#desired_caps['app'] = PATH('D:/appium/app/ContactManager.apk')
desired_caps['appPackage'] = 'com.google.android.apps.messaging'
desired_caps['appActivity'] = '.ui.ConversationListActivity'
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
def tearDown(self):
sleep(1)
self.driver.quit()
def test_text_friend(self):
search_button = self.driver.find_element_by_id("com.google.android.apps.messaging:id/action_zero_state_search").click()
name_search_bar = self.driver.find_element_by_id("com.google.android.apps.messaging:id/zero_state_search_box_auto_complete")
name_search_bar.send_keys("0911111111")
driver.press_keycode(84)
if __name__ == '__main__':
suite =
unittest.TestLoader().loadTestsFromTestCase(ContactsAndroidTests)
unittest.TextTestRunner(verbosity=2).run(suite)
Related
I have two files one is Login_test.py and the other is Financial_Account_Balance.py. When I run the Login file, it works but I want after the system Login, it should check the Financial Account. I keep getting error when I instantiate the Class in the Financial Account Script.
Object has no attribute 'driver'
Below is my code for both files
Login_test
import unittest
from selenium import webdriver
import time
class LoginForm(unittest.TestCase):
def __init__(self, driver = None):
#super().__init__(driver)
if driver is not None:
self.driver = driver
else:
self.setUp()
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r"..\browser\chromedriver.exe")
print("Running Set Up method")
print(self.driver)
self.test_result = None
def test_Login(self):
# We wrap this all in a try/except so we can set pass/fail at the end
try:
# load the page url
print('Loading Url')
self.driver.get('http://localhost:4200/')
# maximize the window
#print('Maximizing window')
self.driver.maximize_window()
# we'll start the login process by entering our username
print('Entering username:')
self.driver.find_element_by_name('username').send_keys('mobile#******.com')
# then by entering our password
print('Entering password:')
self.driver.find_element_by_id('pass').send_keys('*****')
# now we'll click the login button
print('Logging in')
self.driver.find_element_by_class_name("submit").click()
time.sleep(25)
self.test_result = 'pass'
except AssertionError as e:
# log the error message
self.test_result = 'fail'
raise
"""
def tearDown(self):
print("Done with session")
self.driver.quit()
"""
if __name__ == '__main__':
unittest.main()
Financial Account File
from Unit_Test_Files.Login_test import *
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
import time
import logging
import unittest
class FinancialAccountBalance:
#logf = open("Financial_Account_Balance_exception.log", "w")
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.test_finacial()
def setUp(self):
print(self.driver)
print("setup method running")
self.test_finacial()
def test_finacial(self):
try:
print(self.driver)
self.driver.find_element_by_xpath(
'/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[2]/div/input').send_keys(
'Financial Account Balance')
time.sleep(2)
self.driver.find_element_by_xpath(
'/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[2]/div/input').send_keys(
Keys.ENTER)
time.sleep(2)
WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located(
(By.XPATH, '//html/body/chankya-app/chankya-layout/div/ng-sidebar-container'
'/div/div/section/div/div[2]/app-home/div/div/div/div/div[4]'
'/div/div/table/tbody/tr')))
result = self.driver.find_element_by_xpath(
'(/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[4]/div/div/table/tbody/tr)[1]')
result.click()
time.sleep(15)
logging.basicConfig(filename='Financial_Account_Balance.log', level=logging.INFO, filemode='w',
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p ')
logging.info('Date and Time \nReport: Financial Account Balance Automation Test is Successful!!! \n')
print('Financial Account Balance Automation Test is Successful!!!')
except AssertionError as e:
# log the error message
self.test_result = 'fail'
raise
def test_verify(self):
lf = LoginForm()
lf.test_Login()
self.test_finacial()
if __name__ == '__main__':
fa = FinancialAccountBalance()
fa.test_verify()
Error I get when I run the Financial Account file
"C:\Users\Apollo Universe IDS\.virtualenvs\test-cM_nBYrn\Scripts\python.exe" C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py
Financial Account Balance Testing Started...
Traceback (most recent call last):
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 68, in <module>
fa = FinancialAccountBalance()
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 21, in __init__
self.test_finacial()
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 30, in test_finacial
print(self.driver)
AttributeError: 'FinancialAccountBalance' object has no attribute 'driver'
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.test_finacial()
if driver is none , you are not creating any self.driver . so that class will not have any instance variable driver in that case
fix:
class FinancialAccountBalance:
#logf = open("Financial_Account_Balance_exception.log", "w")
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.setUp()
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r"..\browser\chromedriver.exe")
print(self.driver)
print("setup method running")
self.test_finacial()
I wrote a script to save LinkedIn information like: name, last name, graduated university and most important link to LinkedIn script. My script is using Selenium and chromedriver to enter LinkedIn and then scrape. My problem is with saving profile links. Links aren't scraping properly. Here's my code:
import csv
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import parameters
import re
class LinkedIn():
def __init__(self):
self.driver = webdriver.Chrome()
self.people_ls_dic = []
self.csv_name_colums = ["name","degree_connection","zawod","region","opis","firma","link"]
def login(self):
self.driver.get("http://www.linkedin.com/login")
sleep(3)
username = self.driver.find_element_by_name('session_key')
username.send_keys(parameters.linkedin_username)
password = self.driver.find_element_by_name('session_password')
password.send_keys(parameters.linkedin_password)
sign_in_button = self.driver.find_elements_by_xpath('//*[#class="btn__primary--large from__button--floating mercado-button--primary"]')
sign_in_button[0].click()
sleep(5)
def neville_try(self):
sleep(3)
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
profiles = self.driver.find_element_by_xpath('/html/body/div[7]/div[3]/div/div[2]/div/div/div/div[2]/ul')
profiles = profiles.find_elements_by_css_selector('li')
profiles = [(i.text, i.find_element_by_xpath('//*[#data-control-name="entity_result"]').get_attribute('href')) for i in profiles]
print("\n\n")
info_ls = []
for profile, link in profiles:
info_ls.append( (profile.split('\n'), link) )
for iteam, link in info_ls:
if 'Learn more' in iteam:
info_ls.remove(iteam)
print(info_ls)
info_ls = [(iteam, link) for iteam, link in info_ls if iteam != ['']]
for info, link in info_ls:
if info[0] == info[1]:
info.remove(info[1])
try:
name = info[0]
degree_connection = info[2]
zawod = info[3]
region = info[4]
opis = info[5]
opis_f = opis.replace(","," ")
list_of_user_data = [name, zawod, opis_f]
for data in list_of_user_data:
try:
comp = re.findall('at ([a-zA-Z0-9]+)',data)
firma = comp[0]
break
except:
continue
if comp == []:
firma = "brak_danych"
self.people_ls_dic.append({"name":name,"degree_connection":degree_connection,"zawod":zawod,"region":region,"opis":opis,"firma":firma,"link":link})
except:
pass
def go_home(self):
home = self.driver.find_element_by_xpath('//*[#id="inbug-nav-item"]/a')
home.click()
def next_page(self):
sleep(3)
next_p = self.driver.find_element_by_xpath('//*[#aria-label="Next"]')
next_p.click()
def open_people(self):
self.driver.get("https://www.linkedin.com/search/results/people/?origin=DISCOVER_FROM_SEARCH_HOME")
sleep(2)
search_bar = self.driver.find_element_by_xpath('//*[#class="search-global-typeahead__input always-show-placeholder"]')
search_bar.send_keys(parameters.search_query)
search_bar.send_keys(Keys.ENTER)
sleep(3)
def filter_company(self):
cl = self.driver.find_element_by_xpath('//*[#aria-label="Current company filter. Clicking this button displays all Current company filter options."]')
cl.click()
for comp in parameters.list_of_comp:
text = self.driver.find_element_by_xpath('//*[#placeholder="Add a company"]')
text.send_keys(comp)
sleep(1)
filt = self.driver.find_element_by_xpath('/html/body/div[7]/div[3]/div/div[1]/nav/div/div[1]/div/div[2]/ul/li[5]/div/div/div/div[1]/div/form/fieldset/div[1]/div/div/div[2]/div/div[2]')
sleep(0.2)
filt.click()
sleep(1)
apply = self.driver.find_element_by_xpath('/html/body/div[7]/div[3]/div/div[1]/nav/div/div[1]/div/div[2]/ul/li[5]/div/div/div/div[1]/div/form/fieldset/div[2]/button[2]')
apply.click()
sleep(1)
def close(self):
self.driver.close()
def write_to_csv(self):
csv_file = "neville.csv"
with open(csv_file, 'w', encoding="utf-8", newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = self.csv_name_colums)
writer.writeheader()
for data in self.people_ls_dic:
writer.writerow(data)
scrypt = LinkedIn()
scrypt.login()
scrypt.open_people()
ls = range(parameters.ilosc_stron)
scrypt.filter_company()
for i in sorted(ls,reverse=True):
scrypt.neville_try()
if i == 1:
break
scrypt.next_page()
scrypt.write_to_csv()
scrypt.close()
Ofc I have file with parameters and i looks' like this:
linkedin_username = ""
linkedin_password = ""
search_query = 'vcloud director'
list_of_comp = ['Microsoft']
ilosc_stron = 2 //number of pages to click on
I try save screenshot on test failure in python with 'splinter'
1) This code works for Selenium:
# #pytest.fixture(scope="function")
# def browser(request):
# options = Options()
# options.add_argument("--headless")
# options.add_argument("--start-maximized")
# # browser = webdriver.Chrome(ChromeDriverManager().install())
# browser = webdriver.Chrome(options=options)
# browser.implicitly_wait(5)
# failed_before = request.session.testsfailed
# yield browser
# if request.session.testsfailed != failed_before:
# test_name = request.node.name
# take_screenshot(browser, test_name)
# browser.quit()
#
# def take_screenshot(browser, test_name):
# screenshots_dir = "C:\\Users\Ark\\PycharmProjects\\Gop\\Reports"
# screenshot_file_path = "{}/{}.png".format(screenshots_dir, test_name)
# browser.save_screenshot(
# screenshot_file_path)
But doesn't works with Splinter (browser don't close and don't make screenshot):
#pytest.fixture(scope="function")
def browser(request):
options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")
browser = Browser("chrome", headless=False, incognito=True, options=options)
failed_before = request.session.testsfailed
yield browser
if request.session.testsfailed != failed_before:
test_name = request.node.name
take_screenshot(browser, test_name)
browser.quit()
def take_screenshot(browser, test_name):
screenshots_dir = "C:\\Users\Ark\\PycharmProjects\\Gop\\Reports"
screenshot_file_path = "{}/{}.png".format(screenshots_dir, test_name)
browser.save_screenshot(
screenshot_file_path)
print("\n!!! SCREENSHOT OF FAILURE '" + test_name + "' SAVED INTO: '" + screenshots_dir + "' WITH NAME '" + test_name + "'")
2) Or how do this function working? (pytest-splinter)
splinter_make_screenshot_on_failure
https://github.com/pytest-dev/pytest-splinter
Can you help?
I want to testing my tornado server
but, I don't know how...
I don't run my testing code...
please help me unit test on tornado
I don't speak English very well...
I am sorry that I have poor questions.
this is my tornado server code.
import tornado.ioloop
import os
from tornado import web, gen
from concurrent.futures import ThreadPoolExecutor
from json_output import on_correct_text
import json
thread_pool = ThreadPoolExecutor()
class cer(tornado.web.RequestHandler):
_thread_pool = thread_pool
#gen.coroutine
def post(self, json_data):
### temporary json data
_json = {'file_name' : 'tmp_text.txt', 'file_text' : 'temp text...'}
json_data = json.dumps(_json)
tmp_json = {'file_name': '', 'text': '', 'upload_start_timestamp':'', 'upload_end_timestamp': '','process_start_timestamp': '', 'process_end_timestamp': '', 'response_time_second': '', 'status': "upload_waiting"}
json_d = json.loads(json_data)
print(json_d)
jsonString = yield on_correct_text(json_d, tmp_json)
self.set_header("Content-Type", "application/json")
self.write(jsonString)
self.finish()
def make_app():
return tornado.web.Application([
(r"/([a-zA-Z0-9.:_/%{}]+)", cer)
]
)
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
and this is json_output.py
import datetime, time, json
from concurrent.futures import ThreadPoolExecutor
from tornado import gen
thread_pool = ThreadPoolExecutor()
_thread_pool = thread_pool
#gen.coroutine
def on_correct_text(json_data, tmp_json):
file_up_starttime = datetime.datetime.now()
tmp_json['upload_start_timestamp'] = str(file_up_starttime)
tmp_json['status'] = "uploading"
try:
tmp_json['text'] = json_data['file_text']
tmp_json['file_name'] = json_data['file_name']
except:
tmp_json['status'] = "upload_faild"
print("upload falied")
jsonString = json.dumps(tmp_json, ensure_ascii=False)
return jsonString
start_time = time.time()
file_up_endtime = datetime.datetime.now()
tmp_json['upload_end_timestamp'] = str(file_up_endtime)
process_starttime = datetime.datetime.now()
tmp_json['process_start_timestamp'] = str(process_starttime)
tmp_json['status'] = "processing"
try:
process_endtime = datetime.datetime.now()
tmp_json['process_end_timestamp'] = str(process_endtime)
tmp_json['status'] = "complete"
except:
tmp_json['status'] = "process_faild"
print("process falied")
jsonString = json.dumps(tmp_json, ensure_ascii=False)
return jsonString
response_time = round((time.time() - start_time), 2)
tmp_json['response_time_second'] = str(response_time)
jsonString = json.dumps(tmp_json, ensure_ascii=False)
return jsonString
please help me...
I don't know how this tornado server unit test
There is some excellent documentation here on how to setup Unit Testing in Tornado:
http://www.tornadoweb.org/en/stable/testing.html
class cerTester(AsyncHTTPTestCase):
def get_app(self):
return make_app()
def get_url(self, path):
"""Returns an absolute url for the given path on the test server."""
return '%s://localhost:%s%s' % (self.get_protocol(),
self.get_http_port(), path)
def test_url(self):
#This is where your actual test will take place.
response = self.fetch('/sometest', method="POST")
assert response.code == 200
data = json.loads(response.body.decode('utf-8'))
assert data
#More Asserts
I am new to python and I need help with web scraping code to save a dynamic map every week.
This is the site I am interested in.
The purpose is to get to the page, select season, select week, and download image to a local folder. I'll use the image to integrate for an automated weekly report using SAS.
thank you in advance!
import sys
import os
import time
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium import webdriver
import arrow
BASE_URL = 'https://gis.cdc.gov/grasp/fluview/main.html'
DOWNLOAD_PATH = "/Users/"
def closeWebDriver(driver):
if os.name == 'nt':
driver.quit()
else:
driver.close()
def getImage():
profile = FirefoxProfile()
profile.set_preference("browser.download.panel.shown", False)
profile.set_preference("browser.helperApps.neverAsk.openFile","image/png")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "image/png")
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.dir", DOWNLOAD_PATH)
driver = webdriver.Firefox(firefox_profile=profile)
driver.get(BASE_URL)
time.sleep(5)
if not isValidTimeFrame(driver):
print('Not the time to download yet!')
closeWebDriver(driver)
return
selectFirstWeek(driver)
print('- Consume the web.')
wrapper = driver.find_element_by_class_name('downloads-help-area')
download_img_els = wrapper.find_elements_by_class_name('downloads-button')
for el in download_img_els:
text = el.text.encode('utf-8')
# print(text)
if 'download image' == text.strip().lower():
# Process
downloadImage(el)
break
time.sleep(5)
closeWebDriver(driver)
def isValidTimeFrame(driver):
seasons_button = driver.find_element_by_class_name('seasons-button')
time_frame = seasons_button.text.encode('utf-8').strip().lower()
current_year = arrow.now().to('local')
current_year_str = current_year.format('YYYY')
next_year = current_year.shift(years=1)
next_year_str = next_year.format('YY')
print(time_frame)
compare_year = '%s-%s' % (current_year_str, next_year_str)
return time_frame == compare_year
def selectFirstWeek(driver):
prev = driver.find_element_by_id('prevMap')
week = driver.find_element_by_id('weekSlider')
while True:
print(week)
current_number = week.get_property('value')
print('- Week: ' + current_number)
prev.click()
if int(current_number) < 2:
break;
time.sleep(1)
def downloadImage(el):
print('- Click on ' + el.text)
el.click()
getImage()