def main(): login, password = get_credentials() # log-in to Django site if login and password: tw.go(LOGIN_URL) tw.formvalue('1', 'username', login) tw.formvalue('1', 'password', password) tw.submit() if isinstance(DATA_URL, basestring): urls = [DATA_URL] else: urls = list(DATA_URL) # retrieve URIs for url in urls: try: tw.go(url) tw.code('200') tw.show() except TwillAssertionError: code = get_browser().get_code() print(u"Unable to access %(url)s. " u"Received HTTP #%(code)s." % { 'url': url, 'code': code }) tw.reset_browser()
def get_linkedin_viewer_count(username=None, password=None): from twill import get_browser from twill.commands import add_extra_header, go, fv, submit, reset_browser reset_browser() add_extra_header( 'User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.132 Safari/537.36' ) go("https://www.linkedin.com/nhome/") #fv("login", 'session_password', 'LetsTryPrime') #fv("login", 'session_key', '*****@*****.**') fv("login", 'session_key', username) fv("login", 'session_password', password) submit() go('http://www.linkedin.com/wvmx/profile?trk=nav_responsive_sub_nav_wvmp') try: for i in get_browser().result.lxml\ .get_element_by_id('viewers_list-content')\ .iterchildren(): user_listing = simplejson.loads(i.text.replace('\\u002d', '-')) except Exception as e: log.err('Failed to extract user_listing from page: {error}'.format( error=e)) raise LinkedInFailure() try: current_count = user_listing['content']['wvmx_profile_viewers'][ 'viewersCount'] return current_count except KeyError: log.err('Profile view struct in unknown format: {user_listing}'.format( user_listing=user_listing)) raise LinkedInFailure()
def create(etype): """ >> create Project go to <etype>'s creation page """ twc.go('view?etype=%s&vid=creation' % etype)
def edit(rql): """ >> edit "Project P WHERE P eid 123" calls edition view for <rql> """ twc.go('view?rql=%s&vid=edition' % quote(rql))
def test_project_actions(self): # main page tc.go( testlib.PROJECT_LIST_URL ) tc.find("Logged in as") # default project list tc.find("Fly data 19") tc.find("Human HELA 16") tc.find("Mouse project HBB 1") # create a new project name = "Rainbow Connection - New Project" self.create_project(name=name) # visit this new project tc.follow(name) tc.code(200) tc.find("Project: %s" % name) # edit and rename project newname = "Iguana Garden - New Project" tc.follow("Edit") tc.find("Edit Project") tc.fv("1", "name", newname ) tc.fv("1", "info", "Some other *markup* goes here") tc.submit() tc.code(200) tc.notfind(name) tc.find(newname) self.delete_project(name=newname)
def login(username, password): t.add_extra_header("User-Agent", "*****@*****.**") t.go(host + "index.php/Special:UserLogin") t.fv("1", "wpName", username) t.fv("1", "wpPassword", password) t.submit("wpLoginAttempt")
def main(): login, password = get_credentials() # log-in to Django site if login and password: tw.go(LOGIN_URL) tw.formvalue('1', 'username', login) tw.formvalue('1', 'password', password) tw.submit() if isinstance(DATA_URL, basestring): urls = [DATA_URL] else: urls = list(DATA_URL) # retrieve URIs for url in urls: try: tw.go(url) tw.code('200') tw.show() except TwillAssertionError: code = get_browser().get_code() print (u"Unable to access %(url)s. " u"Received HTTP #%(code)s." % {'url': url, 'code': code}) tw.reset_browser()
def test_profile(): """ Test user profile """ go(SITE + '/accounts/profile/') code(404) return
def init(self, **kw): if kw.has_key('stdin'): cmd.Cmd.__init__(self, None, stdin=kw['stdin']) self.use_rawinput = False else: cmd.Cmd.__init__(self) # initialize a new local namespace. namespaces.new_local_dict() # import readline history, if available. if readline: try: readline.read_history_file('.twill-history') except IOError: pass # fail on unknown commands? for test-shell, primarily. self.fail_on_unknown = kw.get('fail_on_unknown', False) # handle initial URL argument if kw.get('initial_url'): commands.go(kw['initial_url']) self._set_prompt() self.names = [] global_dict, local_dict = namespaces.get_twill_glocals() ### add all of the commands from twill. for command in parse.command_list: fn = global_dict.get(command) self.add_command(command, fn.__doc__)
def minitwill(url, script): '''Dada una URL y un script en una versión limitada de twill, ejecuta ese script. Apenas una línea falla, devuelve False. Si todas tienen éxito, devuelve True. Ejemplos: >>> minitwill('http://google.com','code 200') ==> at http://www.google.com.ar/ True >>> minitwill('http://google.com','title bing') ==> at http://www.google.com.ar/ title is 'Google'. False ''' try: go(url) except: return False for line in script.splitlines(): cmd, arg = line.split(' ', 1) try: if cmd in ['code', 'find', 'notfind', 'title']: # Si line es "code 200", esto es el equivalente # de code(200) r = globals()[cmd](arg) except: return False return True
def test_BeautifulSoup(): """ test parsing of BS-processed HTML. """ b = commands.get_browser() commands.config('use_tidy', '0') commands.config('use_BeautifulSoup', '1') commands.config('allow_parse_errors', '0') commands.go(url) ### # Apparently, mechanize is more tolerant than it used to be. # commands.go('/tidy_fixable_html') # forms = [ i for i in b._browser.forms() ] # assert len(forms) == 0, \ # "there should be no correct forms on this page" ### commands.go('/BS_fixable_html') forms = [ i for i in b._browser.forms() ] assert len(forms) == 1, \ "there should be one mangled form on this page"
def login(): if s218: page = 'http://129.21.142.218:8008/securesync/login/' username = '******' password = '******' facility = '0939bcf9d5fe59ff8fde46b5a729a232' else: page = 'http://129.21.142.118:8008/securesync/login/' username = '******' password = '******' facility = 'dbae7005f9b45ce082b5fe0a0985946a' print 'Logging In...' go(page) print "Forms:" showforms() try: # Force try using the first form found on a page. formclear('2') fv("2", "username", username) fv("2", "password", password) fv("2", "facility", facility) #fv("1", "csrfmiddlewaretoken", '3F1bMuIIM9ERzcp6ceEyFxlT51yJKsK6') submit('0') content = showSilently() print 'debug twill post content:', content except urllib2.HTTPError, e: sys.exit("%d: %s" % (e.code, e.msg))
def test_confirm_password_reset(self): """ create confirmation link as Django engine and test it for resetting password """ test_email = '*****@*****.**' go(SITE) code(200) follow('reset password') code(200) fv(2, 'email', test_email) submit() code(200) #create links from django.contrib.auth.tokens import default_token_generator from django.utils.http import int_to_base36 users = User.objects.filter(email__iexact=test_email) for user in users: link = "%s/accounts/password/reset_confirm/%s/%s/" % (SITE, int_to_base36(user.id), default_token_generator.make_token(user)) go(link) code(200) find('Password reset confirm') fv(2, 'new_password1', 'test') fv(2, 'new_password2', 'test') submit() code(200) find('Your password was successfully reseted') self.general_login_action(user.username, 'test', "Welcome, %s" % user.username)
def check_errors(self): """Waits for the tools to finish""" tc.go("./history") page = self.last_page() if page.find('error') > -1: raise AssertionError('Errors in the history for user %s' % self.user)
def test_login_auth(self): """ test login page """ self.general_login_action('user1', 'password1', 'Welcome, user1') go("%s/accounts/login/" % SITE) code(200) url('/accounts/profile/') find('Welcome, user1')
def set_history(self): """Sets the history (stores the cookies for this run)""" if self.history_id: tc.go("./history?id=%s" % self.history_id) else: tc.go("./history") tc.code(200)
def logout(self): "Performs a logout" tc.go( testlib.PROJECT_LIST_URL ) tc.code(200) tc.go("/logout/") tc.code(200) tc.find("You are not logged in")
def get_xml_history(self): """Returns a parsed xml object corresponding to the history""" self.home() tc.go('./history?template=history.xml') xml = self.last_page() tree = ElementTree.fromstring(xml) return tree
def test_project_manager_sharing(self): # test sharing as a manager # main page tc.go( testlib.PROJECT_LIST_URL ) tc.find("Logged in as") # default project list tc.find("Yeast mutant RAV 17") tc.follow("Yeast mutant RAV 17") tc.follow("Sharing") tc.find("Current members") tc.find("Add access") # search for then add Demo User to this project tc.fv("1", "text", "demo" ) tc.submit() tc.code(200) tc.find("Demo User") tc.follow("add as member") tc.find("Demo User") # back to the project view tc.follow("<< return to project") tc.find("Yeast mutant RAV 17")
def test_edit_email_address(self): # Opt out of the periodic emails. This way, the only "checked" # checkbox is the one for if the user's email address gets shown. paulproteus = Person.objects.get() paulproteus.email_me_re_projects = False paulproteus.save() self.login_with_twill() _url = "http://openhatch.org/account/settings/contact-info/" url = make_twill_url(_url) email = "*****@*****.**" # Go to contact info form tc.go(url) # Let's first ensure that "*****@*****.**" doesn't appear on the page. # (We're about to add it.) tc.notfind('checked="checked"') tc.notfind(email) # Edit email tc.fv("a_settings_tab_form", "edit_email-email", email) tc.submit() # Form submission ought to redirect us back to the form. tc.url(url) # Was email successfully edited? tc.find(email) # And does the email address show up on the profile? tc.go(make_twill_url("http://openhatch.org/people/1")) tc.find(email)
def test_project_manager_sharing(self): # test sharing as a manager # main page tc.go(testlib.PROJECT_LIST_URL) tc.find("Logged in as") # default project list tc.find("Yeast mutant RAV 17") tc.follow("Yeast mutant RAV 17") tc.follow("Sharing") tc.find("Current members") tc.find("Add access") # search for then add Demo User to this project tc.fv("1", "text", "demo") tc.submit() tc.code(200) tc.find("Demo User") tc.follow("add as member") tc.find("Demo User") # back to the project view tc.follow("<< return to project") tc.find("Yeast mutant RAV 17")
def handle(msg): print "Handle funct" content_type, chat_type, chat_id = telepot.glance2(msg) data = open("users.txt", "a") if str(chat_id) in open('users.txt').read(): print "User exists" else: data.write(str(chat_id) + " ") data.write( str(msg['chat']['first_name']) + " " + str(msg['chat']['last_name']) + "\n") cmd = str(msg['text']) if cmd == 'Results': bot.sendMessage(chat_id, "Enter USN number to see your results.") elif len(cmd) == 10: bot.sendMessage(chat_id, "Processing") go("http://results.vtu.ac.in/") formclear('1') fv("1", "rid", cmd) submit('submit') save_html(cmd + ".html") lines = open(cmd + '.html').readlines() open(cmd + '.html', 'w').writelines(lines[241:-84]) open(cmd + '.html', 'a').writelines( "@vtu_bot- if this file is empty please check the USN or try again when the results are announced " ) f = open(cmd + '.html', 'rb') response = bot.sendDocument(chat_id, f) else: bot.sendMessage(chat_id, "Please enter a valid USN number")
def get_xml_history(self): """Returns a parsed xml object corresponding to the history""" self.home() tc.go('./history?template=history.xml' ) xml = self.last_page() tree = ElementTree.fromstring(xml) return tree
def visit_loginurl (aggregate): """Check for a login URL and visit it.""" config = aggregate.config url = config["loginurl"] if not url: return if not fileutil.has_module("twill"): msg = strformat.format_feature_warning(module=u'twill', feature=u'login URL visit', url=u'http://twill.idyll.org/') log.warn(LOG_CHECK, msg) return from twill import commands as tc log.debug(LOG_CHECK, u"Visiting login URL %s", url) configure_twill(tc) tc.go(url) if tc.get_browser().get_code() != 200: log.warn(LOG_CHECK, _("Error visiting login URL %(url)s.") % \ {"url": url}) return submit_login_form(config, url, tc) if tc.get_browser().get_code() != 200: log.warn(LOG_CHECK, _("Error posting form at login URL %(url)s.") % \ {"url": url}) return #XXX store_cookies(tc.get_browser().cj, aggregate.cookies, url) resulturl = tc.get_browser().get_url() log.debug(LOG_CHECK, u"URL after POST is %s" % resulturl) # add result URL to check list from ..checker import get_url_from aggregate.urlqueue.put(get_url_from(resulturl, 0, aggregate))
def send(self, msg, *send_to): """ @todo: make use of native vodafone multi-recipients functionality """ for contact in send_to: web.follow(self.SERVICE_URL) try: web.find("/myv/messaging/webtext/Challenge.shtml") except twill.errors.TwillAssertionError, e: pass else: web.go("/myv/messaging/webtext/Challenge.shtml") with tempfile.NamedTemporaryFile(suffix=".jpeg") as captcha: web.save_html(captcha.name) web.back() os.system("open %s " % captcha.name) web.formvalue("WebText", "jcaptcha_response", raw_input("Captcha: ")) web.formvalue("WebText", "message", msg) to = getattr(contact, "mobile", contact) web.formvalue("WebText", "recipient_0", to) web.sleep(2) web.submit() web.code(200) web.find("Message sent!")
def setup( self, login=None, password=None, service_url="https://bramka.play.pl", login_url="https://logowanie.play.pl/p4-idp2/LoginForm.do", logout_url="https://logowanie.play.pl/p4-idp2/LogoutUser", ): self.SERVICE_URL = service_url self.LOGIN_URL = login_url self.LOGOUT_URL = logout_url self.MY_PHONE_NUMBER = login self.MY_PASSWORD = password web.config("readonly_controls_writeable", True) web.agent(self.MY_HTTP_AGENT) web.go(self.SERVICE_URL) web.submit() web.code(200) web.formvalue("loginForm", "login", self.MY_PHONE_NUMBER) web.formvalue("loginForm", "password", self.MY_PASSWORD) web.submit() web.code(200) self._retry_find("editableSmsComposeForm", 5)
def add_class(self, unique_number): class_url = self.url + '/' + unique_number tc.go(class_url) html = StringIO.StringIO() twill.set_output(html) tc.show() soup = BeautifulSoup(html.getvalue()) table = soup.find('table') for row in table.findAll('tr')[1:]: columns = row.findAll('td') unique = columns[0].string days = [d.text for d in columns[1].findAll('span')] hour = [d.text for d in columns[2].findAll('span')] room = [d.text for d in columns[3].findAll('span')] instructor = columns[4].span.text new_course = Course(unique, days, hour, room, instructor) if self._check_planner_to_add(new_course): self.course_set.add(new_course) days_to_add = new_course.parse_days() hours_to_add = new_course.parse_hours() for d in range(len(days_to_add)): for h in range(hours_to_add[d][0], hours_to_add[d][1]): for day in days_to_add[d]: self.grid[h][day] = new_course print("Course successfully added.")
def test_image_processing_library_error(self): """ If the image processing library errors while preparing a photo, report a helpful message to the user and log the error. The photo is not added to the user's profile. """ # Get a copy of the error log. string_log = StringIO.StringIO() logger = logging.getLogger() my_log = logging.StreamHandler(string_log) logger.addHandler(my_log) logger.setLevel(logging.ERROR) self.login_with_twill() tc.go(make_twill_url('http://openhatch.org/people/paulproteus/')) tc.follow('photo') # This is a special image from issue166 that passes Django's image # validation tests but causes an exception during zlib decompression. tc.formfile('edit_photo', 'photo', photo('static/images/corrupted.png')) tc.submit() tc.code(200) self.assert_("Something went wrong while preparing this" in tc.show()) p = Person.objects.get(user__username='******') self.assertFalse(p.photo.name) # an error message was logged during photo processing. self.assert_("zlib.error" in string_log.getvalue()) logger.removeHandler(my_log)
def logout(self): "Performs a logout" tc.go(testlib.PROJECT_LIST_URL) tc.code(200) tc.go("/logout/") tc.code(200) tc.find("You are not logged in")
def login(username): """Find user for given username and make the browser logged in""" global_dict, local_dict = namespaces.get_twill_glocals() # Set a globabl Twill variable to let Twill scripts now the name # of the test, e.g. the directory, as well as community name. #global_dict['test_name'] = test_name #global_dict['community_name'] = test_name + "-testcase" global_dict['cwd'] = os.getcwd() hn = global_dict['localhost_url'] # First logout logout() # Do a login au = global_dict['%s_user' % username] # Echo to screen dump("Logging into %s as %s" % (hn, au)) # Continue ap = global_dict['%s_password' % username] commands.go(hn + '/login.html') commands.fv("formLogin", "login", au) commands.fv("formLogin", "password", ap) commands.submit() # Make sure the login succeeded commands.show() commands.find("My Profile")
def test_detail_automatic_perms(self): tc.go('http://localhost:8080/contactcheck/detail/%s/' % self.check_handle) tc.find('don\'t have permissions') self.authorizer.add_perms('read.contactcheck_automatic') tc.go('http://localhost:8080/contactcheck/detail/%s/' % self.check_handle) tc.notfind('don\'t have permissions') tc.notfind('Invalidate') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('don\'t have permissions') self.authorizer.add_perms('change.contactcheck_automatic') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('Invalidate') tc.notfind('Resolve as failed') self.authorizer.add_perms('add.contactcheck_manual') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('Resolve as failed')
def catalog_find(searchterm, urlfrag, notfind=False): """Just like Twill find, but issues a searchpage-search search""" global_dict, local_dict = namespaces.get_twill_glocals() # This will navigate us away from the place the Twill script is # sitting. Thus, stash away to the current URL, then navigate # back to that URL after searching. br = get_browser() start_url = br.get_url() esc_searchterm = urllib.quote(searchterm) url = "/searchresults.html?body=" + esc_searchterm commands.go(url) # Now do the test. With the fragment of the URL that was # provided, we can do a double-check, to make sure the # searchresults provide that. if notfind: commands.notfind(urlfrag) else: commands.find(urlfrag) # Finally, send them back to the original URL. commands.go(start_url)
def test_project_actions(self): # main page tc.go(testlib.PROJECT_LIST_URL) tc.find("Logged in as") # default project list tc.find("Fly data 19") tc.find("Human HELA 16") tc.find("Mouse project HBB 1") # create a new project name = "Rainbow Connection - New Project" self.create_project(name=name) # visit this new project tc.follow(name) tc.code(200) tc.find("Project: %s" % name) # edit and rename project newname = "Iguana Garden - New Project" tc.follow("Edit") tc.find("Edit Project") tc.fv("1", "name", newname) tc.fv("1", "info", "Some other *markup* goes here") tc.submit() tc.code(200) tc.notfind(name) tc.find(newname) self.delete_project(name=newname)
def get_building_cost(self, id): """ Read the cost for expanding building """ commands.go(SERVER + 'build.php?id=' + str(id)) html = commands.show() soup = BeautifulSoup(html) cost = {} cost['wood'] = int( soup.find('span', { 'class': re.compile('.*r1.*') }).text) cost['clay'] = int( soup.find('span', { 'class': re.compile('.*r2.*') }).text) cost['iron'] = int( soup.find('span', { 'class': re.compile('.*r3.*') }).text) cost['cerial'] = int( soup.find('span', { 'class': re.compile('.*r4.*') }).text) cost['space'] = int( soup.find('span', { 'class': re.compile('.*r5.*') }).text) return cost
def get_cert(cert): try: if not completed_certs.has_key(cert): reset_browser() go('http://www2.fdic.gov/idasp/ExternalConfirmation.asp?inCert1=%s' % (cert)) log.write(cert) html = get_browser().get_html() bhc_links = bhc_cert_href.findall(html) if len(bhc_links) > 0: get_bhc(cert) log.write(' holding\n') else: get_bank(cert) log.write(' bank\n') log.flush() except Exception, e: print e
def __init__ (self, email, password): Browser.go(PANDORA_LOGIN_URL) Browser.formvalue(1, 'login_username', email) Browser.formvalue(1, 'login_password', password) Browser.submit() self.webname = Browser.info().split('/').pop()
def get(url): cmd.go(url) try: cmd.code(200) except TwillAssertionError as s: ff() raise TwillAssertionError('%s url %s' % (s, fullurl(url)))
def delete_agroup(id): post('/py/teacher/agroup/%s/delete/' % id, dict(agroup=id, delete='Delete')) # verify agroup not exists cmd.go('/py/teacher/agroup/list/') cmd.notfind('py/teacher/agroup/%s/' % id)
def leave_all_studentsets_named(studentset_name): b = cmd.get_browser() cmd.go("/py/teacher/studentset/list/") soup = BeautifulSoup(cmd.show()) for tststudentset in soup.findAll('a', text=studentset_name): stsid = int(tststudentset.parent['href'].split('/')[-2]) studentset_leave(stsid)
def student_login(login, password): """ login student by username and password """ cmd.go('/py/student/login/') cmd.fv(1, 'login', login) cmd.fv(1, 'passwd', password) cmd.submit() cmd.find('Attempts/Cards')
def minitwill(url, script): '''Dada una URL y un script en una versión limitada de twill, ejecuta ese script. Apenas una línea falla, devuelve False. Si todas tienen éxito, devuelve True. Ejemplos: >>> minitwill('http://google.com','code 200') ==> at http://www.google.com.ar/ True >>> minitwill('http://google.com','title bing') ==> at http://www.google.com.ar/ title is 'Google'. False ''' go(url) for line in script.splitlines(): cmd, arg = line.split(' ', 1) try: if cmd in ['code', 'find', 'notfind', 'title']: r = globals()[cmd](arg) except: return False return True
def test(): url = twilltestlib.get_url() # test empty page get_title namespaces.new_local_dict() twill.commands.reset_browser() browser = twill.get_browser() try: browser.get_title() assert 0, "should never get here" except TwillException: pass ### now test a few special cases commands.go(url) commands.go('/login') # test no matching forms try: commands.fv('2', 'submit', '1') assert 0 except TwillAssertionError: pass # test regexp match commands.fv('1', '.*you', '1') # test ambiguous match to value commands.go('/testform') commands.fv('1', 'selecttest', 'val') commands.fv('1', 'selecttest', 'value1') commands.fv('1', 'selecttest', 'selvalue1') commands.formclear('1') commands.showforms() try: commands.fv('1', 'selecttest', 'value') assert 0 except TwillException: pass # test ambiguous match to name commands.go('/testform') try: commands.fv('1', 'item_', 'value') assert 0 except Exception: pass try: commands.formfile('1', 'selecttest', 'null') assert 0 except Exception: pass commands.go('http://www.google.com/') browser.get_title() # test the twill script. twilltestlib.execute_twill_script('test-form.twill', initial_url=url)
def test_detail_manual_perms(self): self.verif_mock.getContactCheckDetail.side_effect = self._get_contact_check_func( 'manual') tc.go('http://localhost:8080/contactcheck/detail/%s/' % self.check_handle) tc.find('don\'t have permissions') self.authorizer.add_perms('read.contactcheck_manual') tc.go('http://localhost:8080/contactcheck/detail/%s/' % self.check_handle) tc.notfind('don\'t have permissions') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('don\'t have permissions') self.authorizer.add_perms('change.contactcheck_manual') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('Invalidate') tc.notfind('thank letter') self.authorizer.add_perms('add.contactcheck_thank_you') tc.go('http://localhost:8080/contactcheck/detail/%s/resolve/' % self.check_handle) tc.find('thank letter') tc.notfind('Resolve as failed')
def test_set_avatar(self): self.login_with_twill() for image in [ photo('static/sample-photo.png'), photo('static/sample-photo.jpg') ]: url = 'http://openhatch.org/people/paulproteus/' tc.go(make_twill_url(url)) tc.follow('photo') tc.formfile('edit_photo', 'photo', image) tc.submit() # Now check that the photo == what we uploaded p = Person.objects.get(user__username='******') self.assert_(p.photo.read() == open(image).read()) response = self.login_with_client().get( reverse(mysite.account.views.edit_photo)) self.assertEqual( response.context[0]['photo_url'], p.photo.url, "Test that once you've uploaded a photo via the photo editor, " "the template's photo_url variable is correct.") self.assert_(p.photo_thumbnail) thumbnail_as_stored = mysite.base.depends.Image.open( p.photo_thumbnail.file) w, h = thumbnail_as_stored.size self.assertEqual(w, 40)
def create_task(course_id, name, instructions, template='epf', **kwargs): """ create task and return through_id kwargs - additional parameters """ agroup_id = admin_find_course(id=course_id)['agroup_id'] cmd.go('/py/teacher/agroup/%s/course/%s/task/new/' % (agroup_id, course_id)) cmd.fv(1, 'task_name', name) cmd.fv(1, 'task_template', template) cmd.submit() through_id = cmd.url('.+/task/(?P<task_through_id>\d+)/edit/') cmd.fv(1, 'instructions', instructions) cmd.submit('save') errors = soup().findAll('ul', {'class': 'errorlist'}) if errors: raise AssertionError('Page errors: %s' % errors) cmd.find('Changes saved') return through_id
def set_history(self): """Sets the history (stores the cookies for this run)""" if self.history_id: tc.go( "./history?id=%s" % self.history_id ) else: tc.go( "./history" ) tc.code(200)
def get_bank(cert, get_bhc=False): try: if not completed_certs.has_key(cert): completed_certs[cert] = True go('http://www2.fdic.gov/idasp/confirmation.asp?inCert1=%s&AsOf=9/30/2008' % (cert)) html = get_browser().get_html() bhc_links = bhc_cert_href.findall(html) if bhc_links is not None: for bhc_link in bhc_links: pending_certs.append(bhc_link) save_html('%s_bank.html' % (cert)) fv('1', 'ReportName', '99') submit() fv('2', 'ReportName', '99') submit() save_html('%s_report.html' % (cert)) go('http://www2.fdic.gov/sod/sodInstBranchRpt.asp?rCert=%s&baritem=1&ryear=2008' % (cert)) save_html('%s_sod.html' % (cert)) except Exception, e: print e
def minitwill(url, script): """Dada una URL y un script en una versión limitada de twill, ejecuta ese script. Apenas una línea falla, devuelve False. Si todas tienen éxito, devuelve True. Ejemplos: >>> minitwill('http://google.com','code 200') ==> at http://www.google.com.ar/ True >>> minitwill('http://google.com','title bing') ==> at http://www.google.com.ar/ title is 'Google'. False """ go(url) for line in script.splitlines(): cmd, arg = line.split(" ", 1) try: if cmd in ["code", "find", "notfind", "title"]: r = globals()[cmd](arg) except: return False return True
def test_effed_up_forms2(): """ should always succeed; didn't back ~0.7. """ commands.config('use_tidy', '1') commands.config('use_BeautifulSoup', '1') commands.config('allow_parse_errors', '0') commands.go(url) commands.go('/effed_up_forms2') b = commands.get_browser() forms = b.get_all_forms() form = forms[0] inputs = [i for i in form.inputs] assert len(inputs) == 3, \ "you must have 'tidy' installed for this test to pass" # with a more correct form parser this would work like the above. commands.config('use_tidy', '0') commands.reload() forms = b.get_all_forms() form = forms[0] inputs = [i for i in form.inputs] assert len(inputs) == 3, "lxml should find 3 form inputs"
def visit_loginurl(aggregate): """Check for a login URL and visit it.""" config = aggregate.config url = config["loginurl"] if not url: return if not fileutil.has_module("twill"): msg = strformat.format_feature_warning(module=u'twill', feature=u'login URL visit', url=u'http://twill.idyll.org/') log.warn(LOG_CHECK, msg) return from twill import commands as tc log.debug(LOG_CHECK, u"Visiting login URL %s", url) configure_twill(tc) tc.go(url) if tc.get_browser().get_code() != 200: log.warn(LOG_CHECK, _("Error visiting login URL %(url)s.") % \ {"url": url}) return submit_login_form(config, url, tc) if tc.get_browser().get_code() != 200: log.warn(LOG_CHECK, _("Error posting form at login URL %(url)s.") % \ {"url": url}) return store_cookies(tc.get_browser().cj, aggregate.cookies, url) resulturl = tc.get_browser().get_url() log.debug(LOG_CHECK, u"URL after POST is %s" % resulturl) # add result URL to check list from ..checker import get_url_from aggregate.urlqueue.put(get_url_from(resulturl, 0, aggregate))
def dismod_server_login(): """ login to the dismod server given in dismod3/settings.py.""" twc.go(DISMOD_LOGIN_URL) twc.fv("1", "username", DISMOD_USERNAME) twc.fv("1", "password", DISMOD_PASSWORD) twc.submit() twc.url("accounts/profile")
def login(self): from twill import commands as b b.go('/login') b.fv('login', 'login', 'chris') b.fv('login', 'password', 'chris') b.submit() b.find('You are logged in as chris.')
def test_logout_web(self): self.test_login_web() url = 'http://openhatch.org/search/' url = make_twill_url(url) tc.go(url) tc.notfind('log in') tc.follow('log out') tc.find('log in')
def test_logout_web(self): self.test_login_web() url = "http://openhatch.org/search/" url = make_twill_url(url) tc.go(url) tc.notfind("log in") tc.follow("log out") tc.find("log in")
def run_tool(self, tool_id, **kwd): tool_id = tool_id.replace(" ", "+") """Runs the tool 'tool_id' and pass it the key/values from the *kwd""" tc.go("%s/tool_runner/index?tool_id=%s" % (self.url, tool_id) ) tc.code(200) tc.find('runtool_btn') self.submit_form(**kwd) tc.code(200)
def get_job_queue(): """ fetch list of disease model jobs waiting to run from dismod server given in settings.py. """ dismod_server_login() twc.go(DISMOD_LIST_JOBS_URL) return json.loads(twc.show())