Exemple #1
0
def get_args(require=0):
    """
    >> get_args [<require>]

    Load the command line arguments after the last '--' into $arg1...$argN,
    optionally requiring at least 'require' such arguments.
    """
    from twill import commands, namespaces, shell, errors

    global_dict, local_dict = namespaces.get_twill_glocals()

    require = int(require)

    if len(shell.twillargs) < require:
        from twill.errors import TwillAssertionError
        raise TwillAssertionError("too few arguments; %d rather than %d" % \
                                    (len(shell.twillargs), require,))

    if shell.twillargs:
        for i, arg in enumerate(shell.twillargs):
            global_dict["arg%d" % (i + 1,)] = arg

        print>>commands.OUT, "get_args: loaded %d args as $arg1..$arg%d." % \
                             (i + 1, i + 1)
    else:
        print>>commands.OUT, "no arguments to parse!"
Exemple #2
0
def _run_xpath(xpath):
    _, twill_locals = get_twill_glocals()
    browser = get_browser()
    html = browser.get_html()
    tree = lxml.html.document_fromstring(html)

    try:
        results = tree.xpath(xpath)
    except XPathEvalError:
        err_msg = "Invalid xpath expression: '%s'" % xpath
        log_error(err_msg)
        raise TwillException(err_msg)

    # XXX we aggregate all the values together and warn when there is more than
    # one result
    if results:
        if len(results) > 1:
            log_warn("xpath '%s' found multiple results: using all of them" % xpath)
        result = "\n".join(lxml.html.tostring(r) for r in results)
    else:
        log_error("xpath '%s' found no results")
        result = ""
    # in case we want to cache it at some point
    twill_locals["__xpath_result__"] = result
    twill_locals["__xpath_expr__"] = xpath
    return result
Exemple #3
0
def do_cleanup_for(name):
    if has_cleanup_handler(name) and not options.no_cleanup_mode: 
        log_info("running cleanup handler for %s" % name)
        try:
            suite_data = file(current_namespace[-1].cleanup[name]).read()
            calls = parse_suite(suite_data)
            for script,args,line in calls:
                try:
                    if current_namespace[-1].suites.get(script):
                        log_warn("Cannot call sub-suite %s during cleanup at %s(%d)" % (script,name,line))
                    else:
                        log_info("running cleanup: %s" % name)
                        script_data = read_test(script)
                        try:
                            parameters = make_dict_from_call(args,get_twill_glocals()[0])
                        except (ValueError, TypeError, SyntaxError), e:
                            e.args = ("\"%s%s\": Only positional argument passing is supported in suites." % \
                                          (name, args), ) + e.args[1:]
                            raise e
                        script_data = make_twill_local_defs(parameters) + script_data 
                        twill.execute_string(script_data, no_reset=1)
                except Exception, e:
                    maybe_print_stack() 
                    log_warn("Cleanup call to %s failed at %s(%d)" 
                         % (script + args, name + CLEANUP, line))
        except IOError,e:
            maybe_print_stack()
            log_warn("Unable to read cleanup handler for %s" % name)
        except Exception,e:
            maybe_print_stack()
            log_warn("Exception during cleanup handler for %s" % name)
Exemple #4
0
def _run_xpath(xpath):
    _, twill_locals = get_twill_glocals()
    browser = get_browser()
    html = browser.get_html()
    tree = lxml.html.document_fromstring(html)

    try:
        results = tree.xpath(xpath)
    except XPathEvalError:
        err_msg = "Invalid xpath expression: '%s'" % xpath
        log_error(err_msg)
        raise TwillException(err_msg)

    #XXX we aggregate all the values together and warn when there is more than
    #one result
    if results:
        if len(results) > 1:
            log_warn("xpath '%s' found multiple results: using all of them" %
                     xpath)
        result = '\n'.join(lxml.html.tostring(r) for r in results)
    else:
        log_error("xpath '%s' found no results")
        result = ''
    # in case we want to cache it at some point
    twill_locals['__xpath_result__'] = result
    twill_locals['__xpath_expr__'] = xpath
    return result
Exemple #5
0
def get_args(require=0):
    """
    >> get_args [<require>]

    Load the command line arguments after the last '--' into $arg1...$argN,
    optionally requiring at least 'require' such arguments.
    """
    from twill import commands, namespaces, shell, errors

    global_dict, local_dict = namespaces.get_twill_glocals()

    require = int(require)

    if len(shell.twillargs) < require:
        from twill.errors import TwillAssertionError
        raise TwillAssertionError("too few arguments; %d rather than %d" % \
                                    (len(shell.twillargs), require,))

    if shell.twillargs:
        for i, arg in enumerate(shell.twillargs):
            global_dict["arg%d" % (i + 1, )] = arg

        print("get_args: loaded %d args as $arg1..$arg%d." % \
                             (i + 1, i + 1), file=commands.OUT)
    else:
        print("no arguments to parse!", file=commands.OUT)
Exemple #6
0
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)
Exemple #7
0
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")
Exemple #8
0
def set_random_word(varname):
    """Create a random word based by adding an int to varname """

    global_dict, local_dict = namespaces.get_twill_glocals()

    randint = str(random.randint(100000, 999999))
    global_dict[varname] = varname + randint
Exemple #9
0
def make_intranets(intranets_name):
    """ Make the offices root hierarchy, deleting if it exists"""

    global_dict, local_dict = namespaces.get_twill_glocals()

    global_dict['intranets_name'] = intranets_name

    # Check to see if we have that community, if so, delete it.
    commands.go('/' + intranets_name)
    br = get_browser()
    status = br.get_code()
    if status != 404:
        # The community shouldn't exist, and so we should get 404
        # looking for it.  If no 404, then it exists and we should
        # delete it.
        url = "/%s/delete.html?confirm=1" % intranets_name
        commands.go(url)

    # Now, make the community and make sure it exists
    commands.go("/add_community.html")
    commands.fv("save", "title", intranets_name)
    desc = "Test intranets root created for Twill test case named '%s'"
    commands.fv("save", "description", desc % test_name)
    commands.submit()
    commands.find("Add Existing")
Exemple #10
0
def post_file(form, field, file):
    globals, locals = get_twill_glocals()

    test_path = globals.get('test_path')
    file = os.path.join(test_path, file)
    file = open(file)
    body = file.read()
    file.close()
    fv(form, field, body)
Exemple #11
0
def getmatch(where, what):
     """
     >> getmatch into_var expression

     Evaluates an expression against __match__ and puts it into 'into_var'.
     """
     global_dict, local_dict = get_twill_glocals()
     match = local_dict['__match__']
     local_dict[where] = _do_eval(match, what)
def export_file_contains(filename, content):
    globals, locals = get_twill_glocals()
    z, zipname = globals["__project_export__"]
    if filename not in z.namelist():
        raise TwillAssertionError("file %s not found in project export zipfile" % filename)
    log_warn("inspecting contents of file '%s' in project export zipfile '%s' " % (filename, zipname))
    body = z.read(filename)
    if content not in body:
        raise TwillAssertionError("text '%s' not found in contents of file '%s': %s" % (content, filename, body))
def post_file(form, field, file):
    globals, locals = get_twill_glocals()

    test_path = globals.get("test_path")
    file = os.path.join(test_path, file)
    file = open(file)
    body = file.read()
    file.close()
    fv(form, field, body)
Exemple #14
0
def getmatch(where, what):
    """
     >> getmatch into_var expression

     Evaluates an expression against __match__ and puts it into 'into_var'.
     """
    global_dict, local_dict = get_twill_glocals()
    match = local_dict['__match__']
    local_dict[where] = _do_eval(match, what)
Exemple #15
0
def inspect(filename):
    globals, locals = get_twill_glocals()
    z, zipname = globals['__project_export__']
    if filename not in z.namelist():
        raise TwillAssertionError("file %s not found in project export zipfile" % filename)
    log_warn("inspecting contents of file '%s' in project export zipfile '%s' " % (
            filename, zipname))
    body = z.read(filename)
    import pdb; pdb.set_trace()
def inspect(filename):
    globals, locals = get_twill_glocals()
    z, zipname = globals["__project_export__"]
    if filename not in z.namelist():
        raise TwillAssertionError("file %s not found in project export zipfile" % filename)
    log_warn("inspecting contents of file '%s' in project export zipfile '%s' " % (filename, zipname))
    body = z.read(filename)
    import pdb

    pdb.set_trace()
def download_project_export():
    url = get_browser().get_url()
    assert url.endswith(".zip")
    zipcontents = get_browser().get_html()
    output = StringIO()
    output.write(zipcontents)
    z = zipfile.ZipFile(output, "r")
    name = url.split("/")[-1]
    globals, locals = get_twill_glocals()
    globals["__project_export__"] = (z, name)
Exemple #18
0
def host_alias(old_host, new_host):

    old_host = strip_scheme(old_host)
    new_host = strip_scheme(new_host)
    
    twill_globals, _locals = get_twill_glocals()
    old_host_subst = _substitute_vars(old_host, twill_globals)
    new_host_subst = _substitute_vars(new_host, twill_globals)

    hostname_redirect_mapping[old_host_subst] = new_host_subst
Exemple #19
0
def download_project_export():
    url = get_browser().get_url()
    assert url.endswith(".zip")
    zipcontents = get_browser().get_html()
    output = StringIO()
    output.write(zipcontents)
    z = zipfile.ZipFile(output, 'r')
    name = url.split('/')[-1]
    globals, locals = get_twill_glocals()
    globals['__project_export__'] = (z, name)
Exemple #20
0
def popmatch(which):
    """
     >> popmatch index

     Pops __matchlist__[i] into __match__.
     """
    global_dict, local_dict = get_twill_glocals()

    matchlist = local_dict['__matchlist__']
    match = matchlist.pop(int(which))
    local_dict['__match__'] = match
Exemple #21
0
def popmatch(which):
     """
     >> popmatch index

     Pops __matchlist__[i] into __match__.
     """
     global_dict, local_dict = get_twill_glocals()
     
     matchlist = local_dict['__matchlist__']
     match = matchlist.pop(int(which))
     local_dict['__match__'] = match
Exemple #22
0
def logout():
    """Visit the logout screen"""

    global_dict, local_dict = namespaces.get_twill_glocals()

    # Visit the logout URL
    hn = global_dict['localhost_url']
    commands.go(hn + '/logout')

    # Make sure the login succeeded
    commands.find("Remember me")
Exemple #23
0
def login(username):
   "login to a plone site"
   global parser
   go("/login_form")
   global_dict, local_dict = get_twill_glocals()
   domain = urlparse(local_dict['__url__']).netloc
   global_dict["domain"] = domain
   global_dict["root"] = parser.get(domain, "zoperoot")
   formvalue(2,"__ac_name", username)
   formvalue(2,"__ac_password", parser.get(domain, username))
   submit()
Exemple #24
0
def export_file_contains(filename, content):
    globals, locals = get_twill_glocals()
    z, zipname = globals['__project_export__']
    if filename not in z.namelist():
        raise TwillAssertionError("file %s not found in project export zipfile" % filename)
    log_warn("inspecting contents of file '%s' in project export zipfile '%s' " % (
            filename, zipname))
    body = z.read(filename)
    if content not in body:
        raise TwillAssertionError("text '%s' not found in contents of file '%s': %s" % (
                content, filename, body))
Exemple #25
0
def showvar(which):
     """
     >> showvar var

     Shows the value of the variable 'var'.
     """
     global_dict, local_dict = get_twill_glocals()
     
     d = global_dict.copy()
     d.update(local_dict)
     
     print d.get(str(which))
Exemple #26
0
def send_mail_string(mailStr, base_url=None):
    if base_url is None:
        tglobals, tlocals = get_twill_glocals()
        base_url = tglobals['base_url']

    receiverURL = "%s/send_listen_mail" % base_url.rstrip("/")

    tglobals, tlocals = get_twill_glocals()
    ctx = tglobals.copy()
    ctx.update(tlocals)
    mailStr = substitute_vars(mailStr, ctx)

    mail = email.message_from_string(mailStr)
    body = mail.get_payload()
    sender = mail['From']
    recipient = mail['To']
    subject = mail['Subject']
    log_warn("sending email: Subject: '%s'; From: '%s'; To: '%s'" %
             (subject, sender, recipient))

    send(receiverURL, mailStr)
Exemple #27
0
def send_mail(dir, file, base_url):
    if not os.path.isabs(dir):
        tglobals, tlocals = get_twill_glocals()
        test_path = tglobals['test_path']
        dir = os.path.join(test_path, dir)

    file = os.path.join(dir, file)
    fp = open(file)
    mailStr = fp.read()
    fp.close()

    send_mail_string(mailStr, base_url)
Exemple #28
0
def split(what):
     """
     >> split <regexp>

     Sets __matchlist__ to re.split(regexp, page).
     """
     page = browser.get_html()

     m = re.split(what, page)

     global_dict, local_dict = get_twill_glocals()
     local_dict['__matchlist__'] = m
Exemple #29
0
def split(what):
    """
     >> split <regexp>

     Sets __matchlist__ to re.split(regexp, page).
     """
    page = browser.get_html()

    m = re.split(what, page)

    global_dict, local_dict = get_twill_glocals()
    local_dict['__matchlist__'] = m
Exemple #30
0
def showvar(which):
    """
     >> showvar var

     Shows the value of the variable 'var'.
     """
    global_dict, local_dict = get_twill_glocals()

    d = global_dict.copy()
    d.update(local_dict)

    print d.get(str(which))
Exemple #31
0
def send_mail(dir, file, base_url):
    if not os.path.isabs(dir):
        tglobals, tlocals = get_twill_glocals()
        test_path = tglobals['test_path']
        dir = os.path.join(test_path, dir)

    file = os.path.join(dir, file)
    fp = open(file)
    mailStr = fp.read()
    fp.close()

    send_mail_string(mailStr, base_url)
Exemple #32
0
def send_mail_string(mailStr, base_url=None):
    if base_url is None:
        tglobals, tlocals = get_twill_glocals()
        base_url = tglobals['base_url']

    receiverURL = "%s/send_listen_mail" % base_url.rstrip("/")

    tglobals, tlocals = get_twill_glocals()
    ctx = tglobals.copy()
    ctx.update(tlocals)
    mailStr = substitute_vars(mailStr, ctx)

    mail = email.message_from_string(mailStr)
    body = mail.get_payload()
    sender = mail['From']
    recipient = mail['To']
    subject = mail['Subject']
    log_warn("sending email: Subject: '%s'; From: '%s'; To: '%s'" % (
            subject, sender, recipient))

    send(receiverURL, mailStr)
Exemple #33
0
def css_len(css, num):
    num = int(num)

    _, twill_locals = get_twill_glocals()
    browser = get_browser()
    html = browser.get_html()
    tree = lxml.html.document_fromstring(html)
    sel = CSSSelector(css)
    results = sel(tree)

    actual_num = len(results)
    if actual_num != num:
        raise TwillAssertionError('Expected %s matches to "%s"; found %s' % (num, css, actual_num))
def select_mail_from_header(header, value):
    actuals = []
    _, locals = get_twill_glocals()
    for mailpath in get_mail():
        fp = open(mailpath)
        msg = email.message_from_file(fp)
        fp.close()
        actual = msg.get(header)
        if value == actual:
            locals['__current_mail__'] = mailpath
            return
        actuals.append(actual)
    raise TwillAssertionError("No mail with header %s=%s was sent. Values were:\n%s" % (header, value, pformat(actuals)))
Exemple #35
0
def findall(what):
    """
     >> findall <regexp>

     Sets __matchlist__ to re.findall(regexp, page).
     """
    page = browser.get_html()

    regexp = re.compile(what, re.DOTALL)
    m = regexp.findall(page)

    global_dict, local_dict = get_twill_glocals()
    local_dict['__matchlist__'] = m
Exemple #36
0
def findall(what):
     """
     >> findall <regexp>

     Sets __matchlist__ to re.findall(regexp, page).
     """
     page = browser.get_html()

     regexp = re.compile(what, re.DOTALL)
     m = regexp.findall(page)

     global_dict, local_dict = get_twill_glocals()
     local_dict['__matchlist__'] = m
Exemple #37
0
def find_in_xpath(what, xpath):
    _, twill_locals = get_twill_glocals()
    xpath_result = _run_xpath(xpath)
    # XXX we just ignore case for now
    # if we need to differentiate then we can pass in a flag
    regexp = re.compile(what, re.IGNORECASE)
    m = regexp.search(xpath_result)
    if not m:
        raise TwillAssertionError("no match to '%s' in '%s'" % (what, xpath_result))
    if m.groups():
        match_str = m.group(1)
    else:
        match_str = m.group(0)
    twill_locals["__match__"] = match_str
Exemple #38
0
def css_len(css, num):
    num = int(num)

    _, twill_locals = get_twill_glocals()
    browser = get_browser()
    html = browser.get_html()
    tree = lxml.html.document_fromstring(html)
    sel = CSSSelector(css)
    results = sel(tree)

    actual_num = len(results)
    if actual_num != num:
        raise TwillAssertionError("Expected %s matches to \"%s\"; found %s" %
                                  (num, css, actual_num))
Exemple #39
0
def find_in_xpath(what, xpath):
    _, twill_locals = get_twill_glocals()
    xpath_result = _run_xpath(xpath)
    #XXX we just ignore case for now
    #if we need to differentiate then we can pass in a flag
    regexp = re.compile(what, re.IGNORECASE)
    m = regexp.search(xpath_result)
    if not m:
        raise TwillAssertionError("no match to '%s' in '%s'" %
                                  (what, xpath_result))
    if m.groups():
        match_str = m.group(1)
    else:
        match_str = m.group(0)
    twill_locals['__match__'] = match_str
Exemple #40
0
def setmatch(what):
     """
     >> setmatch expression

     Sets each element __matchlist__ to eval(expression); 'm' is set
     to each element of __matchlist__ prior to processing.
     """
     global_dict, local_dict = get_twill_glocals()
     
     match = local_dict['__matchlist__']
     if isinstance(match, str):         # convert to list
          match = [ match, ]
          
     new_match = [ _do_eval(m, what) for m in match ]
     local_dict['__matchlist__'] = new_match
def run_cat_queue(admin_user, admin_pw):
    globals, locals = get_twill_glocals()

    base_url = globals.get("base_url")
    prepath = globals.get("prepath")

    log_warn("(zope) Running catalog queue for %s" % (base_url))

    scheme, uri = urllib.splittype(base_url)
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    portal.portal_catalog_queue.manage_process()
Exemple #42
0
def run_cat_queue(admin_user, admin_pw): 
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    prepath = globals.get('prepath')

    log_warn("(zope) Running catalog queue for %s" % (base_url))

    scheme, uri = urllib.splittype(base_url) 
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    portal.portal_catalog_queue.manage_process()
Exemple #43
0
def run_test(name, args):

    # this pushes the correct namespace on the stack
    # should be popped
    test = current_namespace[-1].lookup(name)
    if test is None:
        raise NameError("Unable to locate %s or %s in search path" %
                        (name + TEST, name + SUITE))
    name = test

    current = current_namespace[-1]
    try:
        if current.suites.get(name):
            if args:
                log_warn("Arguments provided to suites are ignored! [%s%s]" %
                         (name, args))
            return run_suite(name)
        elif current.tests.get(name):

            # don't do anything in cleanup only mode
            if options.cleanup_mode:
                return []

            try:
                log_info("running test: %s" % name)
                output_stream.indent()
                try:
                    script = file(current.tests[name]).read()
                    try:
                        parameters = make_dict_from_call(
                            args,
                            get_twill_glocals()[0])
                    except (ValueError, TypeError, SyntaxError), e:
                        e.args = ("\"%s%s\": Only positional argument passing is supported in suites." % \
                                      (name, args), ) + e.args[1:]
                        raise e
                    script = make_twill_local_defs(parameters) + script
                    twill.execute_string(script, no_reset=1)
                    return []
                except IOError, e:
                    handle_exception(
                        "Unable to read test '%s'" % (name + TEST), e)
                    return [name]
                except Exception, e:
                    handle_exception("Error running %s" % name, e)
                    return [name]
Exemple #44
0
def add_members(community_name, user1, user2=None):
    """Add one and optionally 2 users to a community"""

    global_dict, local_dict = namespaces.get_twill_glocals()

    l_url = global_dict['localhost_url']
    community_url = urljoin(l_url, 'communities/' + community_name)
    add_member_url = community_url + '/members/add_existing.html'
    commands.go(add_member_url)
    commands.find('Add Existing')
    commands.fv('save', 'users', user1)
    commands.submit()
    if user2:
        commands.go(add_member_url)
        commands.find('Add Existing')
        commands.fv('save', 'users', user2)
        commands.submit()
Exemple #45
0
def livesearch_find(group, term, titleword, notfind=False):
    """See if the term appears in one of the LiveSearch groups"""

    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()

    # We issue a request and get an XML response
    esc_searchterm = urllib.quote(term)
    url = global_dict['localhost_url'] + "/jquery_livesearch?val=" + esc_searchterm
    commands.go(url)
    doc = loads(br.get_html())

    # Grab the correct /response/kind
    kind = ''
    groups = {}
    titles = []
    pre = None
    for result in doc:
        if result['pre'][0:19] == u'<div class="header"':
            # We started a batching group
            pre = result['pre'][20:-6]
            groups[pre] = []

        # We are inside one of the groupings
        title = result['title']
        if titleword in title:
            groups[pre].append(result['title'])

    hasterm = len(groups[group])

    if notfind:
        # Let the _notfind version decide what to do with
        # the error
        return hasterm

    if not hasterm:
        msg = "LiveSearch does not contain %s in group %s"
        raise TwillAssertionError(msg % (term, group))
    else:
        msg = "LiveSearch contains %s in group %s"
        dump(msg % (term, group))
Exemple #46
0
def setmatch(what):
    """
     >> setmatch expression

     Sets each element __matchlist__ to eval(expression); 'm' is set
     to each element of __matchlist__ prior to processing.
     """
    global_dict, local_dict = get_twill_glocals()

    match = local_dict['__matchlist__']
    if isinstance(match, str):  # convert to list
        match = [
            match,
        ]

    new_match = [_do_eval(m, what) for m in match]
    local_dict['__matchlist__'] = new_match
Exemple #47
0
def get_uid(username, admin_user, admin_pw): 
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    prepath = globals.get('prepath')

    log_warn("(zope) Getting uid for user %s on %s" % (username, base_url))

    scheme, uri = urllib.splittype(base_url) 
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    confirmation_code = getattr(portal.portal_memberdata, username).getUserConfirmationCode()

    locals['__uid__'] = confirmation_code
Exemple #48
0
def csv_iterate(filename, scriptname):
    """
    >> csv_iterate <csv_file> <script>

    For each line in <csv_file>, read in a list of comma-separated values,
    put them in $col1...$colN, and execute <script>.
    """
    from twill import namespaces, execute_file

    global_dict, local_dict = namespaces.get_twill_glocals()

    reader = csv.reader(open(filename, "rb"))
    for i, row in enumerate(reader):
        logger.debug('csv_iterate: on row %d of %s', i, filename)
        for i, col in enumerate(row):
            global_dict["col%d" % (i + 1,)] = col

        execute_file(scriptname, no_reset=True)
Exemple #49
0
def get_uid(username, admin_user, admin_pw):
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    prepath = globals.get('prepath')

    log_warn("(zope) Getting uid for user %s on %s" % (username, base_url))

    scheme, uri = urllib.splittype(base_url)
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    confirmation_code = getattr(portal.portal_memberdata,
                                username).getUserConfirmationCode()

    locals['__uid__'] = confirmation_code
Exemple #50
0
def find_in_css(what, css):
    _, twill_locals = get_twill_glocals()
    browser = get_browser()
    html = browser.get_html()
    tree = lxml.html.document_fromstring(html)
    sel = CSSSelector(css)
    results = sel(tree)
    results = '\n'.join(lxml.html.tostring(r) for r in results)

    regexp = re.compile(what, re.IGNORECASE)
    m = regexp.search(results)
    if not m:
        raise TwillAssertionError("no match to '%s' in '%s'" % (what, results))

    if m.groups():
        match_str = m.group(1)
    else:
        match_str = m.group(0)
    twill_locals['__match__'] = match_str
Exemple #51
0
def run_export_queue(admin_user, admin_pw, expected=None):
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    prepath = globals.get('prepath')

    log_warn("(zope) Running export queue for %s" % (base_url))

    scheme, uri = urllib.splittype(base_url) 
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    # pass in a maxwait of 1 second to speed things up
    exports = portal.manage_project_export_queue(1)
    if expected is not None and expected not in exports:
        raise TwillAssertionError("project id %s not found in exported projects: %r" % (expected, exports))
Exemple #52
0
def opencore_user_cleanup(admin_user, admin_pw):
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    prepath = globals.get('prepath')

    log_warn("(zope) Cleaning up local roles for %s" % (base_url))

    scheme, uri = urllib.splittype(base_url)
    host, path = urllib.splithost(uri)
    if prepath is not None:
        path = prepath + path
    auth_url = "%s://%s:%s@%s%s/" % (scheme, admin_user, admin_pw, host, path)
    portal = XMLRPCServer(auth_url)

    try:
        getattr(portal, 'member-postdelete-cleanup')()
    except Fault, e:
        log_warn(
            "could not clean up local roles, maybe your version of opencore doesn't support it?"
        )
Exemple #53
0
def csv_iterate(filename, scriptname):
    """
    >> csv_iterate <csv_file> <script>

    For each line in <csv_file>, read in a list of comma-separated values,
    put them in $col1...$colN, and execute <script>.
    """
    from twill import namespaces, execute_file, commands

    global_dict, local_dict = namespaces.get_twill_glocals()

    reader = csv.reader(open(filename, "rb"))
    for i, row in enumerate(reader):
        if DEBUG:
            print >> commands.OUT, 'csv_iterate: on row %d of %s' % (
                i,
                filename,
            )
        for i, col in enumerate(row):
            global_dict["col%d" % (i + 1, )] = col

        execute_file(scriptname, no_reset=True)
Exemple #54
0
def ensure_project_export(admin_user, admin_pw, project):
    """
    Looks for a project export zipfile in the page.
    (Expects to be already on the project's export view.)
    If no export zipfile is found, trigger the export queue
    processing on the remote server, and then check again.
    """
    globals, locals = get_twill_glocals()

    base_url = globals.get('base_url')
    url = "%s/projects/%s/export/current_status_json" % (
        base_url, project)
    go(url)
    html = get_browser().get_html()
    if "state" not in html:
        run_export_queue(admin_user, admin_pw, project)
    else:
        json = simplejson.loads(html)
        if json['state'] == "failed":
            raise TwillAssertionError(
                "Export failed: %s" % html)
        if json['state'] != 'finished':
            time.sleep(5)
            ensure_project_export(admin_user, admin_pw, project)
Exemple #55
0
def do_cleanup_for(name):
    if has_cleanup_handler(name) and not options.no_cleanup_mode:
        log_info("running cleanup handler for %s" % name)
        try:
            suite_data = file(current_namespace[-1].cleanup[name]).read()
            calls = parse_suite(suite_data)
            for script, args, line in calls:
                try:
                    if current_namespace[-1].suites.get(script):
                        log_warn(
                            "Cannot call sub-suite %s during cleanup at %s(%d)"
                            % (script, name, line))
                    else:
                        log_info("running cleanup: %s" % name)
                        script_data = read_test(script)
                        try:
                            parameters = make_dict_from_call(
                                args,
                                get_twill_glocals()[0])
                        except (ValueError, TypeError, SyntaxError), e:
                            e.args = ("\"%s%s\": Only positional argument passing is supported in suites." % \
                                          (name, args), ) + e.args[1:]
                            raise e
                        script_data = make_twill_local_defs(
                            parameters) + script_data
                        twill.execute_string(script_data, no_reset=1)
                except Exception, e:
                    maybe_print_stack()
                    log_warn("Cleanup call to %s failed at %s(%d)" %
                             (script + args, name + CLEANUP, line))
        except IOError, e:
            maybe_print_stack()
            log_warn("Unable to read cleanup handler for %s" % name)
        except Exception, e:
            maybe_print_stack()
            log_warn("Exception during cleanup handler for %s" % name)
Exemple #56
0
def define_twill_vars(**kwargs):
    tglobals, tlocals = get_twill_glocals()
    tglobals.update(kwargs)
Exemple #57
0
def export_contains(filename):
    globals, locals = get_twill_glocals()
    z, zipname = globals['__project_export__']
    if filename not in z.namelist():
        raise TwillAssertionError("file %s not found in project export zipfile" % filename)
Exemple #58
0
def test():
    url = twilltestlib.get_url()

    # capture output
    fp = StringIO()
    twill.set_output(fp)

    twill.parse.execute_string('code 200', initial_url=url)

    # from file
    twilltestlib.execute_twill_script('test-go.twill', initial_url=url)

    twill.set_output(None)
    assert fp.getvalue()

    ###

    # from stdin
    filename = os.path.join(twilltestlib.testdir, 'test-go.twill')
    old_in, sys.stdin = sys.stdin, open(filename)
    try:
        twilltestlib.execute_twill_script('-', initial_url=url)
    finally:
        sys.stdin = old_in

    # from parse.execute_file
    twill.parse.execute_file('test-go-exit.twill', initial_url=url)

    # also test some failures.

    old_err, sys.stderr = sys.stderr, StringIO()
    try:
        twill.set_errout(sys.stderr)
        #
        # failed assert in a script
        #
        try:
            twill.parse.execute_file('test-go-fail.twill', initial_url=url)
            assert 0
        except TwillAssertionError:
            pass

        commands.go(url)
        try:
            commands.code(400)
            assert 0
        except TwillAssertionError:
            pass

        #
        # no such command (NameError)
        #

        try:
            twill.parse.execute_file('test-go-fail2.twill', initial_url=url)
            assert 0
        except TwillNameError, e:
            pass
    finally:
        sys.stderr = old_err

    namespaces.new_local_dict()
    gd, ld = namespaces.get_twill_glocals()

    commands.go(url)
    try:
        twill.parse.execute_command('url', ('not this', ), gd, ld, "anony")
        assert 0, "shouldn't get here"
    except TwillAssertionError:
        pass

    try:
        commands.follow('no such link')
        assert 0, "shouldn't get here"
    except TwillAssertionError:
        pass

    try:
        commands.find('no such link')
        assert 0, "shouldn't get here"
    except TwillAssertionError:
        pass

    try:
        commands.notfind('Hello')
        assert 0, "shouldn't get here"
    except TwillAssertionError:
        pass

    try:
        twill.parse.execute_command('exit', ('0', ), gd, ld, "anony")
        assert 0, "shouldn't get here"
    except SystemExit:
        pass
Exemple #59
0
def get_local(name, default=None):
    """ return twill Local's variable value """

    g, l = get_twill_glocals()
    return l.get(name, default)
Exemple #60
0
def get_twill_var(varname):
    twill_globals, twill_locals = get_twill_glocals()
    return twill_globals.get(varname)