def login(url, q, p): browser = Browser('chrome') #browser = Browser('webdriver.chrome') # browser = Browser('firefox') browser.visit(url) #time.sleep(5) browser.cookies.add({ 'whatever': 'and ever' }) #https://splinter.readthedocs.io/en/latest/elements-in-the-page.html cookie = browser.cookies.all() print browser.is_element_present_by_xpath('//h1') print cookie #browser.cookies.delete('whatever', 'wherever') # deletes two cookies #browser.cookies.delete() # deletes all cookies #browser.execute_script("$('body').empty()") print browser.evaluate_script("4+4") == 8 #fill in account and password if browser.find_by_id('login_frame'): with browser.get_iframe('login_frame') as frame: frame.find_by_id('switcher_plogin').click() print u'输入账号...' frame.find_by_id('u').fill(q) print u'输入密码...' frame.find_by_id('p').fill(p) print u'尝试登录...' frame.find_by_id('login_button').click() print u'完成登录动作...'
def getPrivNoteURL(message): browser = Browser('phantomjs') #ghost.show() browser.visit("https://privnote.com/") command = "document.getElementById('id_body').value='"+message+"';" result = browser.evaluate_script(command) command = "document.getElementById('button').click();" result = browser.evaluate_script(command) time.sleep(2) command = "document.getElementById('notelink').value;" result = browser.evaluate_script(command) print (result)
def submitQueue(NETID, PASSWORD, SECURITY_QUESTIONS): browser = Browser() # netid page browser.visit("https://puaccess.princeton.edu/psp/hsprod/EMPLOYEE/HRMS/h/?tab=DEFAULT") browser.fill('userid', NETID) browser.find_by_value("Continue").first.click() # password page browser.fill('Bharosa_Password_PadDataField', PASSWORD) browser.evaluate_script("Bharosa_Password_Pad.keyPress('ENTERKEY');") # security question page html = browser.html for key in SECURITY_QUESTIONS.keys(): if key in html: answer = SECURITY_QUESTIONS[key] browser.fill('Bharosa_Challenge_PadDataField', answer) browser.evaluate_script("Bharosa_Challenge_Pad.keyPress('ENTERKEY');") time.sleep(2) # welcome to SCORE browser.find_link_by_text("Student Center").first.click() # student center, start by busting out of the iframe browser.visit("https://puaccess.princeton.edu/psc/hsprod/EMPLOYEE/HRMS/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL?PORTALPARAM_PTCNAV=HC_SSS_STUDENT_CENTER&EOPP.SCNode=HRMS&EOPP.SCPortal=EMPLOYEE&EOPP.SCName=ADMN_SCORE&EOPP.SCLabel=&EOPP.SCPTcname=ADMN_SC_SP_SCORE&FolderPath=PORTAL_ROOT_OBJECT.PORTAL_BASE_DATA.CO_NAVIGATION_COLLECTIONS.ADMN_SCORE.ADMN_S200801281459482840968047&IsFolder=false&PortalActualURL=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL&PortalContentURL=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2fEMPLOYEE%2fHRMS%2fc%2fSA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL&PortalContentProvider=HRMS&PortalCRefLabel=Student%20Center&PortalRegistryName=EMPLOYEE&PortalServletURI=https%3a%2f%2fpuaccess.princeton.edu%2fpsp%2fhsprod%2f&PortalURI=https%3a%2f%2fpuaccess.princeton.edu%2fpsc%2fhsprod%2f&PortalHostNode=HRMS&NoCrumbs=yes&PortalKeyStruct=yes") browser.select('DERIVED_SSS_SCL_SSS_MORE_ACADEMICS', "1005") browser.find_by_id("DERIVED_SSS_SCL_SSS_GO_1").first.click() # pick semester browser.choose("SSR_DUMMY_RECV1$sels$0", "1") browser.find_by_id("DERIVED_SSS_SCT_SSR_PB_GO").first.click() # select classes to add... class should already be in queue browser.find_by_id("DERIVED_REGFRM1_LINK_ADD_ENRL$115$").first.click() # confirm classes browser.find_by_id("DERIVED_REGFRM1_SSR_PB_SUBMIT").first.click()
class WsSimulation(): def __init__(self, username, password, area, playername): self.username = username self.password = password self.area = area self.playername = playername def login(self): c = GetLoginInfo(self.username, self.password) c.getServer() u, p = c.getCookie() s = str(self.area) playername = self.playername self.browser = Browser('chrome') # 访问 URL url = "http://mush.fun" self.browser.visit(url) self.browser.cookies.add({'u': u}) self.browser.cookies.add({'p': p}) self.browser.cookies.add({'s': s}) self.browser.reload() errNum = 0 while not self.browser.is_text_present('登陆'): time.sleep(3) errNum = errNum + 1 if errNum > 5: return False try: # 找到并点击搜索按钮 playerlist = self.browser.find_by_css('.role-list') for item in playerlist: if playername in item.text: item.click() btnlist = self.browser.find_by_xpath('//li[@command="SelectRole"]') btnlist.click() self.browser.evaluate_script("WG.SendCmd('tm 云武神启动')") except Exception as e: return False return True def close(self): self.browser.windows[0].close() def exec_js(self, code, codetype='raid'): try: if codetype == 'ws': self.browser.evaluate_script("WG.SendCmd('{}');".format(code)) else: self.browser.evaluate_script( "ToRaid.perform('{}');".format(code)) except Exception as e: print(e) def get_image(self): screenshot_path = self.browser.screenshot( os.getcwd() + '/absolute_path/{}.png'.format(self.playername), full=True) return screenshot_path
def launch(self): # launch driver browser = Browser('chrome') browser.driver.maximize_window() browser.visit(self.url) #browser.driver.implicitly_wait(5) #browser.driver.Manage().Timeouts().SetPageLoadTimeout(600); for i in range(500): #timeload=browser.evaluate_script('window.performance.timing.domLoading-window.performance.timing.connectStart') #timeload = browser.evaluate_script('window.performance.timing.domComplete - window.performance.timing.fetchStart') #timeload = browser.evaluate_script('window.performance.timing') #print(timeload) try: # if(timeload>1000): # browser.evaluate_script('$(".img-switch-btn").last().click()') browser.reload() browser.driver.set_page_load_timeout(10) browser.driver.set_script_timeout(15) if browser.is_element_present_by_text('下载'): browser.find_by_text('下载').first.click() else: browser.evaluate_script( '$(".img-switch-btn").last().click()') except: try: browser.evaluate_script( '$(".img-switch-btn").last().click()') except: traceback.print_exc() pass #browser.evaluate_script('$(".img-switch-btn").last().click()') time.sleep(1.5) if (len(browser.windows) > 1): browser.windows.current = browser.windows[0] browser.windows.current.close_others() #如果下载不成功则下一张 browser.evaluate_script('$(".img-switch-btn").last().click()') else: browser.evaluate_script('$(".img-switch-btn").last().click()')
alert.text alert.accept() alert.dismiss() prompt = browser.get_alert() prompt.text prompt.fill_with('text') prompt.accept() prompt.dismiss() # use the with statement to interacte with both alerts and prompts with browser.get_alert() as alert: alert.do_stuff() # Executing javascript browser.execute_script("$('body').empty()") browser.evaluate_script("4+4") == 8 # Matchers browser = Browser() browser.visit('https://splinter.readthedocs.io/') browser.is_text_present('splinter') # True browser.is_text_present('splinter', wait_time=10) # True, using wait_time browser.is_not_present('text not present') # True browser.is_element_present_by_css('h1') browser.is_element_present_by_xpath('//h1') browser.is_element_present_by_tag('h1') browser.is_element_present_by_name('name') browser.is_element_present_by_text('Hello World!') browser.is_element_not_present_by_id('firstheader') browser.is_element_not_present_by_value('query')
except: print "Failed on %s" % username continue # get rid of the login overlay try: browser.find_by_css(".cancel").first.click() time.sleep(1) except: pass # scroll to bottom several times for i in range(5): browser.evaluate_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(1) for element in browser.find_by_css(".inline_editor_value"): try: text = element.find_by_css("div").first.find_by_css("div").first.text text_ascii = text.encode('ascii', 'replace') posts.append((username,text_ascii)) except: pass with open("output.csv", "a") as f: csv_out = csv.writer(f) csv_out.writerows(posts)
class SplinterBrowserDriver(BaseBrowserDriver): """ This is a BrowserDriver for splinter (http://splinter.cobrateam.info) that implements the BaseBrowserDriver API. To use it, you must have splinter installed on your env. For itself it's a browser driver that supports multiple browsing technologies such as selenium, phantomjs, zope, etc. """ driver_name = 'splinter' def __init__(self): super(SplinterBrowserDriver, self).__init__() if not splinter_available: raise ImportError( "In order to use splinter Base Driver you have to install it. " "Check the instructions at http://splinter.cobrateam.info") self._browser = Browser(config.default_browser) def _handle_empty_element_action(self, element): if not element: raise ActionNotPerformableException( "The action couldn't be perfomed because the element couldn't " "be found; Try checking if your element" "selector is correct and if the page is loaded properly.") @property def page_url(self): return self._browser.url @property def page_source(self): return self._browser.html @property def page_title(self): return self._browser.title def open_url(self, url): self._browser.driver.get(url) def quit(self): return self._browser.quit() def is_element_visible(self, element): return element.visible def get_element_text(self, element): return element.text def get_element_by_xpath(self, selector): return self._browser.find_by_xpath(selector) def get_element_by_css(self, selector): return self._browser.find_by_css(selector) def get_element_by_id(self, selector): return self._browser.find_by_id(selector) def get_element_by_tag(self, selector): return self._browser.find_by_tag(selector) @element_action def type(self, element, text, slowly=False): return element.type(text, slowly) @element_action def fill(self, element, text): return element.fill(text) @element_action def clear(self, element): self.fill(element, '') @element_action def click(self, element): return element.click() @element_action def check(self, element): return element.check() @element_action def uncheck(self, element): return element.uncheck() @element_action def mouse_over(self, element): return element.mouse_over() @element_action def mouse_out(self, element): return element.mouse_out() def reload(self): return self._browser.reload() def go_back(self): return self._browser.back() def go_forward(self): return self._browser.forward() def execute_script(self, script): return self._browser.evaluate_script(script) def get_iframe(self, iframe_id): return self._browser.get_iframe(iframe_id) def get_alert(self): return self._browser.get_alert() def attach_file(self, input_name, file_path): return self._browser.attach_file(input_name, file_path) def wait_pageload(self, timeout=30): wait_interval = 0.05 elapsed = 0 while self.execute_script('document.readyState') != 'complete': self.wait(wait_interval) elapsed += wait_interval if elapsed > timeout: raise PageNotLoadedException def click_and_wait(self, element, timeout=30): self.click(element) self.wait_pageload(timeout)
for provider in ['us-east-1', 'us-west-2', 'us-west-1', 'eu-west-1', 'ap-southeast-1', 'ap-northeast-1', 'ap-southeast-2','sa-east-1']: browser.visit('https://console.aws.amazon.com/ec2/v2/home?region=%s' % provider) time.sleep(6) #wait to load otherwise it fails browser.find_by_css('.gwt-Button').click() time.sleep(6) browser.find_by_css('#scenario').click() browser.find_by_name('key-pair-method')[2].click() #select no key, because for example ap-southeast-2 does not have the existing keys, #and this asks for a key without letting you to proceed with the images provider_images = [] for i in range (1, len(browser.find_by_css('tr.scenario_description'))): # Check if next image is windows (to ignore it) if 'Windows' in browser.evaluate_script("$('tr.scenario_description').eq(%d).text()" % i): continue # Click image list item browser.execute_script("$('tr.scenario_description').eq(%d).click()" % i) # If 64-bit is available if not browser.evaluate_script("$('tr.scenario_description').eq(%d).find('input#x86_64').attr('disabled')" % i): # Click 64-bit radio button browser.execute_script("$('tr.scenario_description').eq(%d).find('input#x86_64').click()" % i) # Click continue browser.execute_script("$('#qs_continue_scenario .elasticbig-container').click()") # Get image ami line = browser.evaluate_script("$('.wizard_review h1.ami_name').eq(0).text()") ami = 'ami' + line.split(' (ami')[1].replace(')','') title = line.split(' (ami')[0] + ' 64bit'
def scrape(author): print("\nRETRIEVING DATA FOR:", author, "\n") print("\nINITIALIZING CRAWLER\n") # Visit URL browser = Browser( driver_name='chrome', headless=True) #headless=False will show the browser navigation url = "https://scholar.google.com.br/" browser.visit(url) browser.fill('q', author) # Find and click the 'search' button button = browser.find_by_name('btnG') time.sleep(1) # needs to sleep for the button to become active button.click() # If the profile doesn't exist, stop. profile_check = browser.html if "feather-72.png" not in profile_check: print( "\nERROR: PROFILE DOES NOT EXIST. PLEASE CHECK YOUR QUERY OR TYPE ANOTHER NAME.\n" ) return # Find and click the first link (if profile exists). button = browser.find_link_by_partial_href('citations?user='******'gsc_bpf_more') check_button = browser.evaluate_script( 'document.getElementById("gsc_bpf_more").disabled') while check_button == False: time.sleep(1) check_button = browser.evaluate_script( 'document.getElementById("gsc_bpf_more").disabled') button.click() #get html soup = BeautifulSoup(browser.html, 'html.parser') soup.findAll("td", {"class": "gsc_a_t"}) print("\nBUILDING PAPERS DICTIONARY.\n") papers = [] table = soup.find("table", id="gsc_a_t") for tr in table.find_all('tr')[2:]: for td in tr.find_all("td", {"class": "gsc_a_t"}): paper = {} text = re.sub( "[\'\"]", "", tr.find("a", { "class": "gsc_a_at" }).get_text()).strip() # evita erro de sintaxe no sql paper['title'] = text authors = tr.find("div", { "class": "gs_gray" }).get_text().split(',')[:5] authors = [a for a in authors if a != "..." ] # in some cases, the 4th author might be ... authors = [ a.strip().upper() for a in authors ] #remove espaçamento antes de alguns nomes e resolve case sensitiveness authors = [re.sub("[\'\"]", "", a) for a in authors] # evita erro de sintaxe no sql paper['authors'] = authors papers.append(paper) return papers
class HackFreeRice: def __init__(self, browserType='chrome'): self.correct = 0 self.incorrect = 0 self.readCredentials() # Initialize splinter (other possible values include 'phantomjs' and 'firefox') self.browser = Browser(browserType) def initialize(self, verbose=False): # Initialize until it is successful while True: if self.tryInitialize(): if verbose: print 'Successfully initialized.' break def readCredentials(self, verbose=False): # Read credentials from file with open('config') as f: username, password = f.readlines() self.username = username.strip() self.password = password.strip() if verbose: print 'Your username is %s' % self.username print 'Your password is %s' % self.password def tryInitialize(self, verbose=False): # Open freerice self.browser.visit('http://freerice.com/user/login') # Close pop-up, if present if self.browser.is_element_present_by_id('wfp-ew-dialog-close'): if self.browser.find_by_id('wfp-ew-dialog-close').first.visible: # Closed popup if present and visible self.browser.find_by_id('wfp-ew-dialog-close').click() # Login self.browser.execute_script("$('#edit-name').val('%s')" % self.username) self.browser.execute_script("$('#edit-pass').val('%s')" % self.password) self.browser.execute_script("$('#edit-submit').click()") already_logged_in = self.browser.is_text_present('Logout') login_check_string = '%s has earned' % self.username successful_login = self.browser.is_text_present(login_check_string) if already_logged_in or successful_login: if verbose: print 'Successfully logged in!' else: if verbose: print 'Login failed.' return False # Change subject to math self.browser.execute_script("window.location.href = 'http://freerice.com/frapi/category_selected/18492'") if self.browser.is_text_present('Multiplication Table'): if verbose: print 'Successfully navigated to Multiplication Table' return True else: return False def doQuestion(self, verbose=False): # Close twitter solicitation, if present self.browser.execute_script("$('#twt-skip').click()") question_text = self.browser.evaluate_script("$('#question-title').text()") question_text = question_text.split('loader') question_text = ''.join(question_text) if verbose: print 'The question is: %s' % question_text question_text = string.replace(question_text, ' x ', '*').strip() if verbose: print 'The code representation of the question is: %s' % question_text question_answer = self.browser.evaluate_script(question_text) if verbose: print 'The answer is: %s' % question_answer add_id_script = "$('a:contains(\"%s\").answer-item').attr('id', 'clickthisone')" % question_answer if verbose: print 'Script to add id is:', add_id_script self.browser.execute_script(add_id_script) self.browser.find_by_id('clickthisone').click() if self.browser.is_text_present('Correct!'): print 'Got the answer right. Yeah!' self.correct += 1 else: print 'Oops. Got that one wrong.' self.incorrect += 1 print 'You have donated %s grains of rice!' % str(10 * self.correct)
class DashboardTestCase(LiveServerTestCase): """ These tests check basic functions of Sylva's dashboard. """ def setUp(self): self.browser = Browser() socket.setdefaulttimeout(30) signup(self, 'bob', '*****@*****.**', 'bob_secret') def tearDown(self): logout(self) self.browser.quit() @classmethod def tearDownClass(cls): sleep(10) # It needs some time for close the LiverServerTestCase super(DashboardTestCase, cls).tearDownClass() def test_dashboard(self): signin(self, 'bob', 'bob_secret') spin_assert(lambda: self.assertEquals(self.browser.title, 'SylvaDB - Dashboard')) text = self.browser.find_by_xpath( "//header[@class='global']/h1").first.value spin_assert(lambda: self.assertEqual(text, 'Dashboard')) def test_dashboard_new_graph(self): signin(self, 'bob', 'bob_secret') create_graph(self) Graph.objects.get(name="Bob's graph").destroy() def test_dashboard_graph_preview(self): """ This test, after create a graph with data, checks the Sigma visualization running a simple JavaScript code. This code gets the current instance of Sigma and checks the data with Sylva JavaScript object. """ signin(self, 'bob', 'bob_secret') create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() self.browser.is_element_present_by_id('wait_for_js', 3) js_code = ''' var instance = sigma.instances(0); var node = instance.graph.nodes()[0]; sylva.test_node_name = node.properties.Name; ''' self.browser.execute_script(js_code) text = self.browser.evaluate_script('sylva.test_node_name') Graph.objects.get(name="Bob's graph").destroy() spin_assert(lambda: self.assertNotEqual(text.find("Bob's node"), -1)) def test_automatic_tour(self): """ Thist test checks that the tour starts automatically after signup, only once. """ self.browser.is_element_present_by_id('wait_for_cookie_tour', 3) signin(self, 'bob', 'bob_secret') exist = self.browser.is_element_present_by_xpath( "//div[@class='joyride-content-wrapper']") spin_assert(lambda: self.assertEqual(exist, True)) self.browser.visit(self.live_server_url + '/dashboard/') exist = self.browser.is_element_present_by_xpath( "//div[@class='joyride-content-wrapper']") spin_assert(lambda: self.assertNotEqual(exist, True))
from splinter import Browser url = "http://www.premierinn.com" browser = Browser('phantomjs') browser.visit(url) html = browser.evaluate_script("document.documentElement.outerHTML") f = open('testhtml.txt', 'w') f.write(html) f.close
# -*- coding: utf-8 -*- from splinter import Browser import datetime, time browser = Browser('chrome', ) browser.driver.set_window_size(1600, 1000) browser.visit("https://open.weixin.qq.com/") browser.find_by_id("loginBarBt").click() browser.find_by_name("account").fill(u"*****@*****.**") browser.find_by_name("passwd").fill(u"xxx") browser.find_by_text("登录")[2].click() browser.find_by_xpath("//*[@data-param='appid=wxfb1fb56deb2664a8']").click() time.sleep(2) browser.windows.current = browser.windows[1] n = 200 while True: browser.evaluate_script('window.scrollTo(0,%d)'%n) if browser.is_element_present_by_id('js_fastmodify_ip'): break browser.find_by_id('js_fastmodify_ip').first.click() browser.find_by_xpath("/html/body/div[6]/div/div[2]/textarea").fill(u"118.116.127.7") browser.find_by_text('确定').click() time.sleep(2) browser.quit()
class DashboardTestCase(LiveServerTestCase): """ These tests check basic functions of Sylva's dashboard. """ def setUp(self): self.browser = Browser() signup(self, 'bob', '*****@*****.**', 'bob_secret') def tearDown(self): logout(self) self.browser.quit() def test_dashboard(self): signin(self, 'bob', 'bob_secret') self.assertEquals(self.browser.title, 'SylvaDB - Dashboard') text = self.browser.find_by_xpath( "//header[@class='global']/h1").first.value self.assertEqual(text, 'Dashboard') def test_dashboard_new_graph(self): signin(self, 'bob', 'bob_secret') create_graph(self) Graph.objects.get(name="Bob's graph").destroy() def test_dashboard_graph_preview(self): """ This test, after create a graph with data, checks the Sigma visualization running a simple JavaScript code. This code gets the current instance of Sigma and checks the data with Sylva JavaScript object. """ signin(self, 'bob', 'bob_secret') create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() self.browser.is_element_present_by_id('wait_for_js', 3) js_code = ''' var instanceId = '0'; for (key in sigma.instances) { instanceId = key; break; } var instance = sigma.instances[instanceId]; var nodeId = '0'; for (key in sylva.nodes['1']) { nodeId = key; break; } sigma.test_node_id = instance.getNodes(nodeId).id; ''' self.browser.execute_script(js_code) text = self.browser.evaluate_script('sigma.test_node_id') Graph.objects.get(name="Bob's graph").destroy() self.assertNotEqual(text.find("Bob's node"), -1) def test_automatic_tour(self): """ Thist test checks that the tour starts automatically after signup, only once. """ self.browser.is_element_present_by_id('wait_for_cookie_tour', 3) signin(self, 'bob', 'bob_secret') exist = self.browser.is_element_present_by_xpath( "//div[@class='joyride-content-wrapper']") self.assertEqual(exist, True) self.browser.visit(self.live_server_url + '/dashboard/') exist = self.browser.is_element_present_by_xpath( "//div[@class='joyride-content-wrapper']") self.assertNotEqual(exist, True)
class HomePageWebTests(StaticLiveServerTestCase): def setUp(self): self.user1 = UserFactory.build() self.user1.set_password('abc') self.user1.save() self.browser = Browser() def tearDown(self): self.browser.quit() def login_helper(self, username, password): self.browser.visit('%s%s' % (self.live_server_url, '/accounts/login/')) self.browser.fill('username', username) self.browser.fill('password', password) self.browser.find_by_value('Log in').first.click() # Test 2 # Check for login link from anonymous get of homepage def test_anon_login(self): self.browser.visit('%s%s' % (self.live_server_url, '/')) login_link = self.browser.find_by_tag('a')[2] self.assertEqual( '%s%s' % (self.live_server_url, '/accounts/login/'), login_link['href'] ) # Test 3 # Check for register link from anonymous get of homepage def test_anon_register(self): self.browser.visit('%s%s' % (self.live_server_url, '/')) register_link = self.browser.find_by_tag('a')[3] self.assertEqual( '%s%s' % (self.live_server_url, '/accounts/register/'), register_link['href'] ) # Test 4 # Check for user login success def test_login_success(self): self.login_helper(self.user1.username, 'abc') self.assertEqual( self.browser.url, '%s%s' % (self.live_server_url, '/profile/') ) logout_link = self.browser.find_by_tag('a')[6] self.assertEqual( '%s%s' % (self.live_server_url, '/accounts/logout/?next=/'), logout_link['href'] ) greeting = self.browser.find_by_tag('h1')[0] self.assertEqual( '%s%s%s' % ('Well howdy there, ', self.user1.username, '!'), greeting.text ) # Test 5 # Check for user logout success def test_logout_success(self): self.login_helper(self.user1.username, 'abc') self.browser.find_by_tag('a')[6].click() self.assertEqual( self.browser.url, '%s%s' % (self.live_server_url, '/') ) # Test 6 # Register brand new user def test_registration(self): self.browser.visit( '%s%s' % (self.live_server_url, '/accounts/register/') ) self.browser.fill('username', 'joseph') self.browser.fill('email', '*****@*****.**') self.browser.fill('password1', '123') self.browser.fill('password2', '123') self.browser.find_by_value('Submit').first.click() self.assertEqual( self.browser.url, '%s%s' % (self.live_server_url, '/accounts/register/complete/') ) link_end = mail.outbox[0].body.split('days:')[1].split()[0][18:] link = '%s%s' % (self.live_server_url, link_end) self.browser.evaluate_script('document.location="%s"' % link) self.assertEqual( self.browser.url, '%s%s' % (self.live_server_url, '/accounts/activate/complete/') ) self.login_helper('joseph', '123') greeting = self.browser.find_by_tag('h1')[0] self.assertEqual('Well howdy there, joseph!', greeting.text)
class DataNodeTestCase(LiveServerTestCase): """ A set of tests to test all interaction related to the creation and deletion of nodes and relationships. Also, we test export the data in two formats: gexf and csv. """ def setUp(self): self.browser = Browser() socket.setdefaulttimeout(30) signup(self, 'bob', '*****@*****.**', 'bob_secret') signin(self, 'bob', 'bob_secret') def tearDown(self): logout(self) self.browser.quit() @classmethod def tearDownClass(cls): sleep(10) # It needs some time for close the LiverServerTestCase super(DataNodeTestCase, cls).tearDownClass() def test_data_node_addition(self): create_graph(self) create_schema(self) create_type(self) create_data(self) # Check the node name self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() text = self.browser.find_by_id('propertiesTitle').first.value spin_assert(lambda: self.assertEqual(text, 'Properties')) self.browser.find_by_xpath("//span[@class='buttonLinkOption buttonLinkRight']/a").first.click() self.browser.choose('confirm', '1') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath("//div[@class='indent']/div").first.value Graph.objects.get(name="Bob's graph").destroy() spin_assert(lambda: self.assertEqual(text, 'Nodes: 0')) def test_data_node_addition_rel_add_del(self): create_graph(self) create_schema(self) create_type(self) create_node(self, "Bob") create_node(self, "Alice") # We create a allowed relation js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill("This the allowed relationship for Bob's graph") self.browser.find_by_value('Save Type').first.click() spin_assert(lambda: self.assertEqual( self.browser.title, "SylvaDB - Bob's graph")) # We create the link between the nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath("//td[@class='dataActions']/a[@class='dataOption list']").first.click() self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath("//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", 5) self.browser.find_by_xpath("//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b").first.click() self.browser.find_by_value("Save Bob's type").first.click() # Delete the relationship self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath("//span[@class='all-relationships incoming-relationships i_bobs_rel1-relationships']//a[@class='delete-row initial-form floating']").first.click() self.browser.find_by_value("Save Bob's type").first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value spin_assert(lambda: self.assertEqual(text, "0 relationships")) Graph.objects.get(name="Bob's graph").destroy() def test_node_type_deletion_keeping_nodes(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value spin_assert(lambda: self.assertNotEqual(text.find("Bob's rel"), -1)) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath("//td[@class='dataActions']/a[@class='dataOption list']").first.click() self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath("//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath("//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b").first.click() self.browser.find_by_value("Save Bob's type").first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value spin_assert(lambda: self.assertEqual(text, "1 relationships")) # Deleting type js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_xpath("//fieldset[@class='module aligned wide model']/h2/a").first.click() self.browser.find_by_xpath("//span[@class='buttonLinkOption buttonLinkRight']/a[@class='delete']").first.click() text = self.browser.find_by_xpath( "//p/label[@for='id_option_0']").first.value spin_assert(lambda: self.assertNotEqual(text.find( "We found some elements of this type"), -1)) # Keeping nodes self.browser.choose('option', 'no') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath( "//div[@class='body-inside']/p").first.value spin_assert(lambda: self.assertEqual( text, 'There are no types defined yet.')) # Checking self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-nodes']").first.value spin_assert(lambda: self.assertEqual(text, "2 nodes")) text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value spin_assert(lambda: self.assertEqual(text, "1 relationships")) text = self.browser.find_by_xpath( "//div[@class='graph-empty-message']").first.value spin_assert(lambda: self.assertNotEqual( text.find("Your Schema is empty."), -1)) Graph.objects.get(name="Bob's graph").destroy() def test_node_type_deletion_deleting_nodes(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value spin_assert(lambda: self.assertNotEqual(text.find("Bob's rel"), -1)) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath("//td[@class='dataActions']/a[@class='dataOption list']").first.click() self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath("//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath("//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b").first.click() self.browser.find_by_value("Save Bob's type").first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value spin_assert(lambda: self.assertEqual(text, "1 relationships")) # Deleting type js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_xpath("//fieldset[@class='module aligned wide model']/h2/a").first.click() self.browser.find_by_xpath("//span[@class='buttonLinkOption buttonLinkRight']/a[@class='delete']").first.click() text = self.browser.find_by_xpath( "//p/label[@for='id_option_0']").first.value spin_assert(lambda: self.assertNotEqual(text.find( "We found some elements of this type"), -1)) # Deleting nodes self.browser.choose('option', 'de') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath( "//div[@class='body-inside']/p").first.value spin_assert(lambda: self.assertEqual( text, 'There are no types defined yet.')) # Checking self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-nodes']").first.value spin_assert(lambda: self.assertEqual(text, "0 nodes")) text = self.browser.find_by_xpath("//div[@class='flags-block']/span[@class='graph-relationships']").first.value spin_assert(lambda: self.assertEqual(text, "0 relationships")) Graph.objects.get(name="Bob's graph").destroy() def test_data_node_clone(self): create_graph(self) create_schema(self) create_type(self) create_data(self) original_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[1].value # Clone the node self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td/a[@class='edit']").first.click() self.browser.find_by_name('Name').first.fill(original_name + " clone") self.browser.find_by_name("as-new").first.click() # Check that two nodes exist original_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[1].value clone_name = self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td")[4].value spin_assert(lambda: self.assertEqual(original_name, "Bob's node")) spin_assert(lambda: self.assertEqual(clone_name, "Bob's node clone")) Graph.objects.get(name="Bob's graph").destroy() def test_sigma_visualization_in_node_view(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value spin_assert(lambda: self.assertNotEqual(text.find("Bob's rel"), -1)) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath("//td[@class='dataActions']/a[@class='dataOption list']").first.click() self.browser.find_by_xpath("//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath("//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath("//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b").first.click() self.browser.find_by_value("Save Bob's type").first.click() # Checking self.browser.find_by_xpath("//table[@id='content_table']/tbody/tr/td/a[@title='View node']/p[text()='Alice']").first.click() self.browser.is_element_present_by_id('wait_for_js', 3) js_code = ''' var instance = sigma.instances(0); sylva.test_node_count = instance.graph.nodes().length; ''' self.browser.execute_script(js_code) text = self.browser.evaluate_script('sylva.test_node_count') spin_assert(lambda: self.assertEqual(text, 2)) Graph.objects.get(name="Bob's graph").destroy() def test_graph_export_gexf(self): create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_by_id('toolsMenu').first.click() cookies = {self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"]} result = requests.get(self.live_server_url + '/tools/bobs-graph/export/gexf/', cookies=cookies) spin_assert(lambda: self.assertEqual( result.headers['content-type'], 'application/xml')) spin_assert(lambda: self.assertEqual( self.browser.status_code.is_success(), True)) fw = open('sylva/sylva/tests/files/bobs-graph.gexf', 'w') fw.write(result.content) fw.close() f = open('sylva/sylva/tests/files/bobs-graph.gexf') xmlFile = "" for line in f: xmlFile += line f.close() spin_assert(lambda: self.assertEqual(xmlFile, result.content)) Graph.objects.get(name="Bob's graph").destroy() def test_graph_export_csv(self): create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_by_id('toolsMenu').first.click() cookies = {self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"]} result = requests.get(self.live_server_url + '/tools/bobs-graph/export/csv/', cookies=cookies) spin_assert(lambda: self.assertEqual( result.headers['content-type'], 'application/zip')) spin_assert(lambda: self.assertEqual( self.browser.status_code.is_success(), True)) test_file = StringIO(result.content) csv_zip = ZipFile(test_file) for name in csv_zip.namelist(): fw = open('sylva/sylva/tests/files/' + name, 'w') fw.write(csv_zip.read(name)) fw.close() for name in csv_zip.namelist(): f = open('sylva/sylva/tests/files/' + name) csvFile = "" for line in f: csvFile += line f.close() spin_assert(lambda: self.assertEqual(csv_zip.read(name), csvFile)) Graph.objects.get(name="Bob's graph").destroy()
class DashboardTestCase(LiveServerTestCase): """ These tests check basic functions of Sylva's dashboard. """ def setUp(self): self.browser = Browser() socket.setdefaulttimeout(30) signup(self, "bob", "*****@*****.**", "bob_secret") def tearDown(self): logout(self) self.browser.quit() @classmethod def tearDownClass(cls): sleep(10) # It needs some time for close the LiverServerTestCase super(DashboardTestCase, cls).tearDownClass() def test_dashboard(self): signin(self, "bob", "bob_secret") spin_assert(lambda: self.assertEquals(self.browser.title, "SylvaDB - Dashboard")) text = self.browser.find_by_xpath("//header[@class='global']/h1").first.value spin_assert(lambda: self.assertEqual(text, "Dashboard")) def test_dashboard_new_graph(self): signin(self, "bob", "bob_secret") create_graph(self) Graph.objects.get(name="Bob's graph").destroy() def test_dashboard_graph_preview(self): """ This test, after create a graph with data, checks the Sigma visualization running a simple JavaScript code. This code gets the current instance of Sigma and checks the data with Sylva JavaScript object. """ signin(self, "bob", "bob_secret") create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_link_by_href("/graphs/bobs-graph/").first.click() self.browser.is_element_present_by_id("wait_for_js", 3) js_code = """ var instance = sigma.instances(0); var node = instance.graph.nodes()[0]; sylva.test_node_name = node.properties.Name; """ self.browser.execute_script(js_code) text = self.browser.evaluate_script("sylva.test_node_name") Graph.objects.get(name="Bob's graph").destroy() spin_assert(lambda: self.assertNotEqual(text.find("Bob's node"), -1)) def test_automatic_tour(self): """ Thist test checks that the tour starts automatically after signup, only once. """ self.browser.is_element_present_by_id("wait_for_cookie_tour", 3) signin(self, "bob", "bob_secret") exist = self.browser.is_element_present_by_xpath("//div[@class='joyride-content-wrapper']") spin_assert(lambda: self.assertEqual(exist, True)) self.browser.visit(self.live_server_url + "/dashboard/") exist = self.browser.is_element_present_by_xpath("//div[@class='joyride-content-wrapper']") spin_assert(lambda: self.assertNotEqual(exist, True))
class DataNodeTestCase(LiveServerTestCase): """ A set of tests to test all interaction related to the creation and deletion of nodes and relationships. Also, we test export the data in two formats: gexf and csv. """ def setUp(self): self.browser = Browser() signup(self, 'bob', '*****@*****.**', 'bob_secret') signin(self, 'bob', 'bob_secret') def tearDown(self): logout(self) self.browser.quit() def test_data_node_addition(self): create_graph(self) create_schema(self) create_type(self) create_data(self) # Check the node name self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() text = self.browser.find_by_id('propertiesTitle').first.value self.assertEqual(text, 'Properties') self.browser.find_by_xpath( "//span[@class='buttonLinkOption buttonLinkRight']/a").first.click( ) self.browser.choose('confirm', '1') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath( "//div[@class='indent']/div").first.value Graph.objects.get(name="Bob's graph").destroy() self.assertEqual(text, 'Nodes: 0') def test_data_node_addition_rel_add_del(self): create_graph(self) create_schema(self) create_type(self) create_node(self, "Bob") create_node(self, "Alice") # We create a allowed relation js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill('Bob\'s rel') self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'This the allowed relationship for Bob\'s graph') self.browser.find_by_value('Save Type').first.click() self.assertEqual(self.browser.title, "SylvaDB - Bob's graph") # We create the link between the nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath( "//td[@class='dataActions']/a[@class='dataOption list']" ).first.click() self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath( "//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", 5) self.browser.find_by_xpath( "//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b" ).first.click() self.browser.find_by_value('Save Bob\'s type').first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "1 relationships") # Delete the relationship self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath( "//td[@class='dataActions']/a[@class='dataOption list']" ).first.click() self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath( "//span[@class='all-relationships incoming-relationships i_bobs_rel1-relationships']//a[@class='delete-row initial-form floating']" ).first.click() self.browser.find_by_value('Save Bob\'s type').first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "0 relationships") Graph.objects.get(name="Bob's graph").destroy() def test_node_type_deletion_keeping_nodes(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value self.assertNotEqual(text.find("Bob's rel"), -1) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath( "//td[@class='dataActions']/a[@class='dataOption list']" ).first.click() self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath( "//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath( "//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b" ).first.click() self.browser.find_by_value('Save Bob\'s type').first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "1 relationships") # Deleting type js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_xpath( "//fieldset[@class='module aligned wide model']/h2/a").first.click( ) self.browser.find_by_xpath( "//span[@class='buttonLinkOption buttonLinkRight']/a[@class='delete']" ).first.click() text = self.browser.find_by_xpath( "//p/label[@for='id_option_0']").first.value self.assertNotEqual(text.find("We found some elements of this type"), -1) # Keeping nodes self.browser.choose('option', 'no') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath( "//div[@class='body-inside']/p").first.value self.assertEqual(text, 'There are no types defined yet.') # Checking self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-nodes']" ).first.value self.assertEqual(text, "2 nodes") text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "1 relationships") self.browser.is_element_present_by_id('wait_for_js', 3) js_code = ''' var instanceId = '0'; for (key in sigma.instances) { instanceId = key; break; } var instance = sigma.instances[instanceId]; sigma.test_node_count = instance.getNodesCount(); ''' self.browser.execute_script(js_code) text = self.browser.evaluate_script('sigma.test_node_count') self.assertEqual(text, 0) Graph.objects.get(name="Bob's graph").destroy() def test_node_type_deletion_deleting_nodes(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value self.assertNotEqual(text.find("Bob's rel"), -1) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath( "//td[@class='dataActions']/a[@class='dataOption list']" ).first.click() self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath( "//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath( "//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b" ).first.click() self.browser.find_by_value('Save Bob\'s type').first.click() self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "1 relationships") # Deleting type js_code = "$('a#schema-link')[0].click();" self.browser.execute_script(js_code) self.browser.find_by_xpath( "//fieldset[@class='module aligned wide model']/h2/a").first.click( ) self.browser.find_by_xpath( "//span[@class='buttonLinkOption buttonLinkRight']/a[@class='delete']" ).first.click() text = self.browser.find_by_xpath( "//p/label[@for='id_option_0']").first.value self.assertNotEqual(text.find("We found some elements of this type"), -1) # Deleting nodes self.browser.choose('option', 'de') self.browser.find_by_value('Continue').first.click() text = self.browser.find_by_xpath( "//div[@class='body-inside']/p").first.value self.assertEqual(text, 'There are no types defined yet.') # Checking self.browser.find_link_by_href('/graphs/bobs-graph/').first.click() text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-nodes']" ).first.value self.assertEqual(text, "0 nodes") text = self.browser.find_by_xpath( "//div[@class='flags-block']/span[@class='graph-relationships']" ).first.value self.assertEqual(text, "0 relationships") Graph.objects.get(name="Bob's graph").destroy() def test_data_node_clone(self): create_graph(self) create_schema(self) create_type(self) create_data(self) original_name = self.browser.find_by_xpath( "//table[@id='content_table']/tbody/tr/td")[1].value # Clone the node self.browser.find_by_xpath( "//table[@id='content_table']/tbody/tr/td/a[@class='edit']" ).first.click() self.browser.find_by_name('Name').first.fill(original_name + " clone") self.browser.find_by_name("as-new").first.click() # Check that two nodes exist original_name = self.browser.find_by_xpath( "//table[@id='content_table']/tbody/tr/td")[1].value clone_name = self.browser.find_by_xpath( "//table[@id='content_table']/tbody/tr/td")[4].value self.assertEqual(original_name, "Bob's node") self.assertEqual(clone_name, "Bob's node clone") Graph.objects.get(name="Bob's graph").destroy() def test_sigma_visualization_in_node_view(self): create_graph(self) create_schema(self) create_type(self) # Adding relationship to the type self.browser.find_by_id('allowedRelations').first.click() self.browser.select('source', '1') self.browser.find_by_name('name').fill("Bob's rel") self.browser.select('target', '1') self.browser.find_by_id('id_description').fill( 'The loved relationship') self.browser.find_by_value('Save Type').first.click() text = self.browser.find_by_xpath( "//div[@class='form-row indent']/label").first.value self.assertNotEqual(text.find("Bob's rel"), -1) # Creating nodes create_node(self, 'Bob') create_node(self, 'Alice') # Creating relationship between nodes self.browser.find_by_id('dataMenu').first.click() self.browser.find_by_xpath( "//td[@class='dataActions']/a[@class='dataOption list']" ).first.click() self.browser.find_by_xpath( "//td[@class='dataList']/a[@class='edit']").first.click() self.browser.find_by_xpath( "//li[@class='token-input-input-token']/input").first.fill('Alice') self.browser.is_element_present_by_id("id_user_wait", wait_time=5) self.browser.find_by_xpath( "//div[@class='token-input-dropdown']//li[@class='token-input-dropdown-item2 token-input-selected-dropdown-item']/b" ).first.click() self.browser.find_by_value('Save Bob\'s type').first.click() # Checking self.browser.find_by_xpath( "//table[@id='content_table']/tbody/tr/td/p/a[@title='View node' and text()='Alice']" ).first.click() self.browser.is_element_present_by_id('wait_for_js', 3) js_code = ''' var instanceId = '0'; for (key in sigma.instances) { instanceId = key; break; } var instance = sigma.instances[instanceId]; sigma.test_node_count = instance.getNodesCount(); ''' self.browser.execute_script(js_code) text = self.browser.evaluate_script('sigma.test_node_count') self.assertEqual(text, 2) Graph.objects.get(name="Bob's graph").destroy() def test_graph_export_gexf(self): create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_by_id('toolsMenu').first.click() cookies = { self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"] } result = requests.get(self.live_server_url + '/tools/bobs-graph/export/gexf/', cookies=cookies) self.assertEqual(result.headers['content-type'], 'application/xml') self.assertEqual(self.browser.status_code.is_success(), True) fw = open('sylva/base/tests/files/bobs-graph.gexf', 'w') fw.write(result.content) fw.close() f = open('sylva/base/tests/files/bobs-graph.gexf') xmlFile = "" for line in f: xmlFile += line f.close() self.assertEqual(xmlFile, result.content) Graph.objects.get(name="Bob's graph").destroy() def test_graph_export_csv(self): create_graph(self) create_schema(self) create_type(self) create_data(self) self.browser.find_by_id('toolsMenu').first.click() cookies = { self.browser.cookies.all()[0]["name"]: self.browser.cookies.all()[0]["value"], self.browser.cookies.all()[1]["name"]: self.browser.cookies.all()[1]["value"] } result = requests.get(self.live_server_url + '/tools/bobs-graph/export/csv/', cookies=cookies) self.assertEqual(result.headers['content-type'], 'application/zip') self.assertEqual(self.browser.status_code.is_success(), True) test_file = StringIO(result.content) csv_zip = ZipFile(test_file) for name in csv_zip.namelist(): fw = open('sylva/base/tests/files/' + name, 'w') fw.write(csv_zip.read(name)) fw.close() for name in csv_zip.namelist(): f = open('sylva/base/tests/files/' + name) csvFile = "" for line in f: csvFile += line f.close() self.assertEqual(csv_zip.read(name), csvFile) Graph.objects.get(name="Bob's graph").destroy()
def angular_app_loaded(browser: Browser) -> bool: """Check that the angular app is loaded.""" code = 'window.hasOwnProperty("adhocracy") '\ '&& window.adhocracy.hasOwnProperty("loadState") '\ '&& window.adhocracy.loadState === "complete";' return browser.evaluate_script(code)
from splinter import Browser import time import sys # copy t.html to tomcat/webapp/ROOT/ # this demo shows that js can't change the class of element. browser = Browser('chrome') browser.visit("http://localhost:8080/t.html") time.sleep(2) browser.evaluate_script( 'document.getElementById("p1").style.fontFamily="Arial"') time.sleep(2) browser.evaluate_script('document.getElementById("p2").style.color="red"') time.sleep(2) browser.evaluate_script( 'document.getElementById("p3").style.fontFamily="Arial"') browser.evaluate_script('document.getElementById("p3").style.color="gray"') time.sleep(2) browser.evaluate_script('document.getElementById("p4").style.fontSize="30px"') time.sleep(2) browser.evaluate_script('document.getElementById("p1").class="bodyChange"') time.sleep(2) browser.evaluate_script('document.getElementById("p2").class="body"')
class SplinterBrowserDriver(BaseBrowserDriver): """ This is a BrowserDriver for splinter (http://splinter.cobrateam.info) that implements the BaseBrowserDriver API. To use it, you must have splinter installed on your env. For itself it's a browser driver that supports multiple browsing technologies such as selenium, phantomjs, zope, etc. """ driver_name = 'splinter' def __init__(self): super(SplinterBrowserDriver, self).__init__() if not splinter_available: raise ImportError( "In order to use splinter Base Driver you have to install it. " "Check the instructions at http://splinter.cobrateam.info") self._browser = Browser(config.default_browser) def _handle_empty_element_action(self, element): if not element: raise ActionNotPerformableException( "The action couldn't be perfomed because the element couldn't " "be found; Try checking if your element" "selector is correct and if the page is loaded properly.") @property def page_url(self): return self._browser.url @property def page_source(self): return self._browser.html @property def page_title(self): return self._browser.title def open_url(self, url): self._browser.driver.get(url) def quit(self): return self._browser.quit() def is_element_visible(self, element): return element.visible def get_element_text(self, element): return element.text def get_element_by_xpath(self, selector): return self._browser.find_by_xpath(selector) def get_element_by_css(self, selector): return self._browser.find_by_css(selector) def get_element_by_id(self, selector): return self._browser.find_by_id(selector) def get_element_by_tag(self, selector): return self._browser.find_by_tag(selector) @element_action def type(self, element, text, slowly=False): return element.type(text, slowly) @element_action def fill(self, element, text): return element.fill(text) @element_action def clear(self, element): self.fill(element, '') @element_action def click(self, element): return element.click() @element_action def check(self, element): return element.check() @element_action def uncheck(self, element): return element.uncheck() @element_action def mouse_over(self, element): return element.mouse_over() @element_action def mouse_out(self, element): return element.mouse_out() def reload(self): return self._browser.reload() def go_back(self): return self._browser.back() def go_forward(self): return self._browser.forward() def execute_script(self, script): """This method is deprecated. Use `execute_javascript` instead. """ return self._browser.evaluate_script(script) def execute_javascript(self, script): return self._browser.evaluate_script(script) def get_iframe(self, iframe_id): return self._browser.get_iframe(iframe_id) def get_alert(self): return self._browser.get_alert() def attach_file(self, input_name, file_path): return self._browser.attach_file(input_name, file_path) def wait_pageload(self, timeout=30): wait_interval = 0.05 elapsed = 0 while self.execute_javascript('document.readyState') != 'complete': self.wait(wait_interval) elapsed += wait_interval if elapsed > timeout: raise PageNotLoadedException def click_and_wait(self, element, timeout=30): self.click(element) self.wait_pageload(timeout)
'Runner.instance_.horizon.obstacles[0].xPos') if (xPos < 120): return True else: return False undefinedX = True groundY = 23 trexX = 93 trexWidth = 44 browser = Browser('chrome') browser.visit('chrome://dino') jump() while True: if browser.evaluate_script('Runner.instance_.crashed'): while True: print("dead") if undefinedX: try: xpos = browser.evaluate_script( 'Runner.instance_.horizon.obstacles[0].xPos') undefinedX = False except selenium.common.exceptions.WebDriverException: pass else: if browser.evaluate_script('Runner.instance_.crashed'): undefinedX = True jump() else: if (isObstacleClose()):