gnunet-svn
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUnet-SVN] [taler-wallet-webex] branch master updated (b4525c56 -> 5d8


From: gnunet
Subject: [GNUnet-SVN] [taler-wallet-webex] branch master updated (b4525c56 -> 5d816ca0)
Date: Thu, 02 Nov 2017 16:21:14 +0100

This is an automated email from the git hooks/post-receive script.

marcello pushed a change to branch master
in repository wallet-webex.

    from b4525c56 increse selenium timeout
     new c3595fe4 experimenting with logs
     new 77e9eb9d indent
     new a55daa79 withdraw returns boolean
     new 38185fb1 finishing to fix returned values from Selenium routines, plus 
general simplification of code.
     new ca2073c2 instantiating and using_one_ wait object, plus porting all 
DOM operations to use waits.
     new d4e8b989 abort() doesn't log anymore
     new 5d816ca0 bundling args in a class

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 selenium/chrome_responsive.py |   2 +
 selenium/withdraw_buy.py      | 337 ++++++++++++++++++++----------------------
 2 files changed, 166 insertions(+), 173 deletions(-)
 mode change 100644 => 100755 selenium/chrome_responsive.py
 mode change 100644 => 100755 selenium/withdraw_buy.py

diff --git a/selenium/chrome_responsive.py b/selenium/chrome_responsive.py
old mode 100644
new mode 100755
index 9d9ab41f..483e2dba
--- a/selenium/chrome_responsive.py
+++ b/selenium/chrome_responsive.py
@@ -41,5 +41,7 @@ parser.add_argument('--remote', help="Points webdriver.Remote 
at URI", metavar="
 args = parser.parse_args()
 ret = client_setup(args)
 logger.info("Chromium is responsive")
+for entry in ret.get_log("browser"):
+    print(entry.get("message"))
 time.sleep(3)
 ret.close()
diff --git a/selenium/withdraw_buy.py b/selenium/withdraw_buy.py
old mode 100644
new mode 100755
index 766cdc77..c886329a
--- a/selenium/withdraw_buy.py
+++ b/selenium/withdraw_buy.py
@@ -22,18 +22,27 @@ import os
 import re
 import json
 
-logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
+logging.basicConfig(format='%(levelname)s: %(message)s',
+    level=logging.INFO)
 logger = logging.getLogger(__name__)
-taler_baseurl = os.environ.get('TALER_BASEURL', 'https://test.taler.net/')
+taler_baseurl = os.environ.get('TALER_BASEURL',
+    'https://test.taler.net/')
 display = Display(visible=0, size=(1024, 768))
 
-def abort(client):
-    client.quit()
+class TestContext():
+    def __init__(self, client):
+        self.client = client
+        self.wait = WebDriverWait(client, 20)
+
+def kill_display():
     if hasattr(display, "old_display_var"):
-        print("Kill display")
         display.stop()
-    sys.exit(1)
 
+# All the operations we need upon errors.
+def abort(client):
+    client.quit()
+    kill_display()
+    sys.exit(1)
 
 def client_setup(args):
     """Return a dict containing the driver and the extension's id"""
@@ -52,11 +61,10 @@ def client_setup(args):
     if not args.withhead:
         display.start()
     if args.remote:
-        client = webdriver.Remote(desired_capabilities=cap, 
command_executor=args.remote)
+        client = webdriver.Remote(desired_capabilities=cap,
+            command_executor=args.remote)
     else:
-        logger.info("About to get chromed")
         client = webdriver.Chrome(desired_capabilities=cap)
-        logger.info("Got chromed")
     client.get('https://taler.net')
 
     listener = """\
@@ -74,15 +82,6 @@ def client_setup(args):
     logger.info("Extension ID: %s" % str(ext_id))
     return {'client': client, 'ext_id': ext_id}
 
-def is_error(client):
-    """Return True in case of errors in the browser, False otherwise"""
-    for log_type in ['browser']:
-        for log in client.get_log(log_type):
-            if log['level'] is 'error':
-                print(log['level'] + ': ' + log['message'])
-                return True
-        return False
-
 def print_log(client):
     print("--- Dumping browser log: ---")
     for log in client.get_log("browser"):
@@ -90,237 +89,229 @@ def print_log(client):
     print("--- End of browser log ---")
 
 
-def switch_base():
-    """If 'test' is in TALER_BASEURL, then make it be 'demo', and viceversa.
-    Used to trig currency mismatch errors. It assumes that the 
https://{test,demo}.taler.net
-    layout is being used"""
-    global taler_baseurl
-    url = parse.urlparse(taler_baseurl)
-    if url[1] == 'test.taler.net':
-        taler_baseurl = "https://demo.taler.net";
-    if url[1] == 'demo.taler.net':
-        taler_baseurl = "https://test.taler.net";
-
-def make_donation(client, amount_menuentry=None):
-    """Make donation at donations.test.taler.net. Assume the wallet has coins.
-    Just donate to the default receiver"""
-    client.get(parse.urljoin(taler_baseurl, "donations"))
+def make_donation(ctx, amount_menuentry):
+    """Make donation at donations.test.taler.net. Assume
+    the wallet has coins.  Just donate to the default receiver"""
+    ctx.client.get(parse.urljoin(taler_baseurl, "donations"))
     try:
-        form = client.find_element(By.TAG_NAME, "form")
+        form = ctx.wait.until(EC.visibility_of_element_located((By.TAG_NAME,
+            "form")))
     except NoSuchElementException:
         logger.error('No donation form found')
-        abort(client)
-    if amount_menuentry:
-        xpath_menu = '//address@hidden"taler-donation"]'
-        try:
-            dropdown = client.find_element(By.XPATH, xpath_menu)
-            for option in dropdown.find_elements_by_tag_name("option"):
-                if option.get_attribute("innerHTML") == amount_menuentry:
-                    option = WebDriverWait(client, 
10).until(EC.visibility_of(option))
-                    logger.info("Picked donation %s" % option.text)
-                    option.click()
-                    break
-        except NoSuchElementException:
-            logger.error("value '" + str(amount_value) + "' is not offered by 
this shop to donate, please adapt it")
-            abort(client)
-    form.submit() # amount and receiver chosen
-    wait = WebDriverWait(client, 10)
+        return False
+    xpath_menu = '//address@hidden"taler-donation"]'
+    try:
+        dropdown = ctx.client.find_element(By.XPATH, xpath_menu)
+        for option in dropdown.find_elements_by_tag_name("option"):
+            if option.get_attribute("innerHTML") == amount_menuentry:
+                option = ctx.wait.until(EC.visibility_of(option))
+                option.click()
+                break
+    except NoSuchElementException:
+        logger.error("amount '" + str(amount_value) + "\
+            ' is not offered by this shop to donate")
+        return False
+    form.submit()
     try:
-        confirm_taler = wait.until(EC.element_to_be_clickable((By.ID, 
"select-payment-method")))
-        logger.info("confirm_taler: %s" % 
confirm_taler.get_attribute("outerHTML"))
+        confirm_taler = ctx.wait.until(EC.element_to_be_clickable((By.ID,
+            "select-payment-method")))
     except NoSuchElementException:
         logger.error('Could not trigger contract on donation shop')
-        abort(client)
-    confirm_taler.click() # Taler as payment option chosen
+        return False
+    confirm_taler.click()
     try:
-        confirm_pay = wait.until(EC.element_to_be_clickable((By.XPATH,
+        confirm_pay = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
             "//address@hidden'pure-button button-success']"))) 
     except TimeoutException:
         logger.error('Could not confirm payment on donation shop')
-        abort(client)
+        return False
     confirm_pay.click()
+    return True
+
+# Check if the current page is displaying the article
+# whose title is 'title'.
 
-def check_article(client, title):
+def check_article(ctx, title):
     try:
-        client.find_element(By.XPATH, "//h1[contains(., '%s')]" % 
title.replace("_", " "))
+        ctx.wait.until(EC.visibility_of_element_located((By.XPATH,
+            "//h1[contains(., '%s')]" % title.replace("_", " "))))
     except NoSuchElementException:
-        logger.error("Article not correctly bought")
-        client.quit()
-        display.stop()
+        logger.error("Article '%s' not shown on this (%s) page\
+        " % (title, ctx.client.current_url))
         return False
     return True
 
 
-def buy_article(client, title, fulfillment_url=None):
-    """Buy article at shop.test.taler.net. Assume the wallet has coins.
-       Return False if some error occurs, the fulfillment URL otherwise"""
+def buy_article(ctx, title, fulfillment_url=None):
+    """Buy article at shop.test.taler.net. Assume the wallet
+    has coins.  Return False if some error occurs, the fulfillment
+    URL otherwise"""
+
     if fulfillment_url:
-        client.get(fulfillment_url)
-        if check_article(client, title):
+        ctx.client.get(fulfillment_url)
+        if check_article(ctx, title):
             return fulfillment_url
         return False
-
-    client.get(parse.urljoin(taler_baseurl, "shop"))
-    wait = WebDriverWait(client, 20)
-
+    ctx.client.get(parse.urljoin(taler_baseurl, "shop"))
     try:
-        teaser = wait.until(EC.element_to_be_clickable((By.XPATH, 
"//h3/address@hidden"/essay/%s\"]" % title)))
-        
-        logger.info("Scrolling to article position: %s", teaser.location['y'])
-        client.execute_script("window.scrollBy(30, %s)" % teaser.location['y'])
+        teaser = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
+            "//h3/address@hidden"/essay/%s\"]" % title)))
+        ctx.client.execute_script("window.scrollBy(30, %s)" % 
teaser.location['y'])
         teaser.click()
     except (NoSuchElementException, TimeoutException) as e:
         logger.error("Could not choose chapter '%s'" % title)
-        abort(client)
+        return False
     time.sleep(1)
     try:
-        confirm_pay = wait.until(EC.element_to_be_clickable((By.XPATH,
+        confirm_pay = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
             "//address@hidden'pure-button button-success']"))) 
-        logger.info("Pay button turned clickable")
     except TimeoutException:
-        logger.error('Could not confirm payment on blog (timed out)')
-        print_log(client)
-        abort(client)
+        logger.error('Could not confirm contract on blog (timed out)')
+        return False
     confirm_pay.click()
     time.sleep(3)
-    if not check_article(client, title):
+    if not check_article(ctx, title):
         return False
-    return client.current_url
+    return ctx.client.current_url
 
-def register(client):
-    """Register a new user to the bank delaying its execution until the
-    profile page is shown"""
-    client.get(parse.urljoin(taler_baseurl, "bank"))
+def register(ctx):
+    """Register a new user to the bank delaying its execution
+    until the profile page is shown"""
+    ctx.client.get(parse.urljoin(taler_baseurl, "bank"))
     try:
-        register_link = client.find_element(By.XPATH, 
"//address@hidden'/accounts/register/']")
+        register_link = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
+            "//address@hidden'/accounts/register/']")))
     except NoSuchElementException:
         logger.error("Could not find register link on bank's homepage")
-        abort(client)
+        return False
     register_link.click()
     try:
-        client.find_element(By.TAG_NAME, "form")
+        ctx.wait.until(EC.visibility_of_element_located((By.TAG_NAME, "form")))
     except NoSuchElementException:
         logger.error("Register form not found")
-        abort(client)
-
+        return False
     register = """\
         var form = document.getElementsByTagName('form')[0];
         form.username.value = '%s';
         form.password.value = 'test';
         form.submit();
-        """ % str(int(time.time())) # need fresh username
-
-    client.execute_script(register)
-    # need implicit wait to be set up
+        """ % str(int(time.time()))
+    ctx.client.execute_script(register)
     try:
-        button = client.find_element(By.ID, "select-exchange")
+        ctx.wait.until(EC.element_to_be_clickable((By.ID,
+            "select-exchange")))
     except NoSuchElementException:
         logger.error("Selecting exchange impossible")
-        abort(client)
-    # when button is gotten, the browser is in the profile page
-    # so the function can return
-    if not is_error(client):
-        logger.info('Correctly registered at bank')
-    else:
-        logger.error('User not registered at bank')
+        return False
+    return True
 
 
-def withdraw(client, amount_menuentry=None):
+def withdraw(ctx, amount_menuentry):
     """Register and withdraw (1) KUDOS for a fresh user"""
-    register(client)
-    logger.info("Withdrawing..")
-    wait = WebDriverWait(client, 10)
     # trigger withdrawal button
     try:
-        button = client.find_element(By.ID, "select-exchange")
+        button = ctx.wait.until(EC.element_to_be_clickable((By.ID,
+            "select-exchange")))
     except NoSuchElementException:
         logger.error("Selecting exchange impossible")
-        abort(client)
-    if amount_menuentry:
-        xpath_menu = '//address@hidden"reserve-amount"]'
-        try:
-            dropdown = client.find_element(By.XPATH, xpath_menu)
-            for option in dropdown.find_elements_by_tag_name("option"):
-                if option.get_attribute("innerHTML") == amount_menuentry:
-                    option = WebDriverWait(client, 
10).until(EC.visibility_of(option))
-                    option.click()
-                    break
-        except NoSuchElementException:
-            logger.error("value '" + str(amount_value) + "' is not offered by 
this bank to withdraw, please adapt it")
-            abort(client)
-    # confirm amount
-    logger.info("About to confirm amount")
+        return False
+    xpath_menu = '//address@hidden"reserve-amount"]'
+    try:
+        # No need to wait: if 'button' above exists, then
+        # menu elements do.
+        dropdown = ctx.client.find_element(By.XPATH, xpath_menu)
+        for option in dropdown.find_elements_by_tag_name("option"):
+            if option.get_attribute("innerHTML") == amount_menuentry:
+                option = ctx.wait.until(EC.visibility_of(option))
+                option.click()
+                break
+    except NoSuchElementException:
+        logger.error("amount '" + str(amount_value) + "' \
+            is not offered by this bank to withdraw")
+        return False
     button.click()
-    logger.info("Exchange confirmation refreshed")
     # Confirm exchange (in-wallet page)
     try:
-        logger.info("Polling for the button")
-        accept_exchange = wait.until(EC.element_to_be_clickable((By.XPATH, 
"//address@hidden'pure-button button-success']")))
+        accept_exchange = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
+            "//address@hidden'pure-button button-success']")))
     except TimeoutException:
         logger.error("Could not confirm exchange")
-        abort(client)
-    # This click returns the captcha page (put wait?)
-    logger.info("About to confirm exchange")
+        return False
     accept_exchange.click()
     try:
-        accept_fees = wait.until(EC.element_to_be_clickable((By.XPATH, 
"//button[1]")))
-    except TimeoutException:
-        logger.error("Could not accept fees")
-        abort(client)
-    accept_fees.click()
-    # Properly wait for the next page to be loaded?
-    try:
-        answer = client.find_element(By.XPATH, "//address@hidden'pin_0']")
-        question = client.find_element(By.XPATH, 
"//address@hidden'captcha-question']/div")
+        answer = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
+            "//address@hidden'pin_0']")))
+        question = ctx.wait.until(EC.element_to_be_clickable((By.XPATH,
+            "//address@hidden'captcha-question']/div")))
+
     except NoSuchElementException:
-        logger.error("Captcha page not gotten or malformed")
-        abort(client)
+        logger.error("Captcha page unavailable or malformed")
+        return False
     questionTok = question.text.split()
     op1 = int(questionTok[2])
     op2 = int(questionTok[4])
     res = {'+': op1 + op2, '-': op1 - op2, u'\u00d7': op1 * op2}
     answer.send_keys(res[questionTok[3]])
     try:
-        form = client.find_element(By.TAG_NAME, "form")
+        # No need to wait, if CAPTCHA elements exists
+        # then submitting button has to.
+        form = ctx.client.find_element(By.TAG_NAME, "form")
     except NoSuchElementException:
-        logger.error("Could not submit captcha answer (therefore trigger 
withdrawal)")
-        abort(client)
+        logger.error("Could not submit captcha answer")
+        return False
     form.submit()
     # check outcome
     try:
-        client.find_element(By.CLASS_NAME, "informational-ok")
+        ctx.wait.until(EC.presence_of_element_located((By.CLASS_NAME,
+            "informational-ok")))
     except NoSuchElementException:
         logger.error("Withdrawal not completed")
-        abort(client)
-    logger.info("Withdrawal completed")
-
+        return False
+    return True
 
 parser = argparse.ArgumentParser()
-parser.add_argument('--ext', help="packed extension (.crx file)", 
metavar="CRX", type=str, dest="ext")
-parser.add_argument('--ext-unpacked', help="loads unpacked extension from 
directory", metavar="EXTDIR", type=str, dest="extdir")
-parser.add_argument('--remote', help="Whether the test is to be run against 
URI, or locally", metavar="URI", type=str, dest="remote")
-parser.add_argument('--with-head', help="Graphically shows the browser (useful 
to debug)", action="store_true", dest="withhead")
+parser.add_argument('--ext', help="packed extension (.crx file)",
+    metavar="CRX", type=str, dest="ext")
+parser.add_argument('--ext-unpacked',
+    help="loads unpacked extension from directory",
+    metavar="EXTDIR", type=str, dest="extdir")
+parser.add_argument('--remote',
+    help="Whether the test is to be run against URI, or locally",
+    metavar="URI", type=str, dest="remote")
+parser.add_argument('--with-head',
+    help="Graphically shows the browser (useful to debug)",
+    action="store_true", dest="withhead")
 args = parser.parse_args()
-logger.info("testing against " + taler_baseurl)
-logger.info("Getting extension's ID..")
-ret = client_setup(args)
-logger.info("Creating the browser driver..")
-client = ret['client']
-client.implicitly_wait(10)
-withdraw(client, "10.00 TESTKUDOS")
-# FIXME: wait for coins appropriately
-time.sleep(2)
-logger.info("Buying article..")
-fulfillment_url_25 = buy_article(client, "25._The_Danger_of_Software_Patents")
-fulfillment_url_41 = buy_article(client, "41._Avoiding_Ruinous_Compromises")
-client.delete_all_cookies()
-ret = buy_article(client, "25._The_Danger_of_Software_Patents", 
fulfillment_url_25)
-logger.info("Donating..")
-make_donation(client, "1.0 TESTKUDOS")
-# FIXME: better clearing the cache before replaying the payment
-logger.info("Payment replayed: '%s'" % ret)
-logger.info("Test passed")
-client.quit()
-if hasattr(display, "old_display_var"):
-    display.stop()
+
+ctx = TestContext(client_setup(args)['client'])
+
+if not register(ctx):
+    print_log(ctx.client)
+    abort(ctx.client)
+
+if not withdraw(ctx, "10.00 TESTKUDOS"):
+    print_log(ctx.client)
+    abort(ctx.client)
+
+fulfillment_url_25 = buy_article(ctx,
+    "25._The_Danger_of_Software_Patents")
+
+if not fulfillment_url_25:
+    print_log(ctx.client)
+    abort(ctx.client)
+
+ctx.client.delete_all_cookies()
+
+if not buy_article(ctx, "25._The_Danger_of_Software_Patents",
+    fulfillment_url_25):
+    print_log(ctx.client)
+    logger.error("Could not replay payment")
+    abort(ctx.client)
+
+if not make_donation(ctx, "1.0 TESTKUDOS"):
+    print_log(ctx.client)
+    abort(ctx.client)
+
+ctx.client.quit()
+kill_display()
 sys.exit(0)

-- 
To stop receiving notification emails like this one, please contact
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]