Exemplo n.º 1
0
def dt_row_cnt(check = (),
              quiet = True):
    """ return the rows that are being displayed and the total rows in the dataTable """
    config = current.test_config
    browser = config.browser

    elem = browser.find_element_by_id("list_info")
    details = elem.text
    if not quiet:
        s3_debug(details)
    words = details.split()
    start = int(words[1])
    end = int(words[3])
    length = int(words[5])
    filtered = None
    if len(words) > 10:
        filtered = int(words[9])
    if check != ():
        if len(check ) == 3:
            expected = "Showing %d to %d of %d entries" % check
            actual = "Showing %d to %d of %d entries" % (start, end, length)
            assert (start, end, length) == check, "Expected result of '%s' doesn't equal '%s'" % (expected, actual)
        elif len(check) == 4:
            expected = "Showing %d to %d of %d entries (filtered from %d total entries)" % check
            if filtered:
                actual = "Showing %d to %d of %d entries (filtered from %d total entries)" % (start, end, length, filtered)
            else:
                actual = "Showing %d to %d of %d entries" % (start, end, length)
            assert (start, end, length, filtered) == check, "Expected result of '%s' doesn't equal '%s'" % (expected, actual)
    if len(words) > 10:
        return (start, end, length, filtered)
    else:
        return (start, end, length)
Exemplo n.º 2
0
def logout():
    """ Logout """

    config = current.test_config
    browser = config.browser

    url = "%s/default/user/login" % config.url
    browser.get(url)

    browser.find_element_by_id("auth_menu_email").click()

    try:
        elem = browser.find_element_by_id("auth_menu_logout")
    except NoSuchElementException:
        s3_debug("Logged-out already")
        return True

    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        assert 0, "Logout unsuccesful"
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 3
0
def logout():
    """ Logout """

    config = current.test_config
    browser = config.browser

    url = "%s/default/user/login" % config.url
    browser.get(url)

    try:
        elem = browser.find_element_by_id("auth_menu_logout")
    except NoSuchElementException:
        s3_debug("Logged-out already")
        return True

    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        assert 0, "Logout unsuccesful"
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 4
0
 def helper_inv_track_send_item(self, user, send_id, data, removed=True):
     """
         Helper method to add a track item to the inv_send with the
         given send_id by the given user
     """
     try:
         add_btn = self.browser.find_element_by_id("show-add-btn")
         if add_btn.is_displayed():
             add_btn.click()
     except:
         pass
     self.login(account=user, nexturl="inv/send/%s/track_item" % send_id)
     table = "inv_track_item"
     result = self.create(table, data, dbcallback = self.dbcallback_getStockLevels)
     # Get the last record in the before & after
     # this will give the stock record which has been added to the end by
     # the getStockLevels callback
     if removed:
         qnty = 0
         for line in data:
             if line[0] == "quantity":
                 qnty = float(line[1])
                 break
         stock_before = result["before"].records[len(result["before"])-1].quantity
         stock_after = result["after"].records[len(result["after"])-1].quantity
         stock_shipped = qnty
         self.assertTrue( stock_before - stock_after == stock_shipped, "Warehouse stock not properly adjusted, was %s should be %s but is recorded as %s" % (stock_before, stock_after, stock_before - stock_shipped))
         s3_debug ("Stock level before %s, stock level after %s" % (stock_before, stock_after))
     return result
Exemplo n.º 5
0
    def recv_shipment(self, user, recv_id, data):
        """
            Helper method that will receive the shipment, adding the
            totals that arrived
    
            It will get the stock in the warehouse before and then after
            and check that the stock levels have been properly increased
        """

        db = current.db
        s3db = current.s3db
        rvtable = s3db.inv_recv
        iitable = s3db.inv_inv_item
        # First get the site_id
        query = (rvtable.id == recv_id)
        record = db(query).select(rvtable.site_id, limitby=(0, 1)).first()
        site_id = record.site_id
        # Now get all the inventory items for the site
        query = (iitable.site_id == site_id)
        before = db(query).select(orderby=iitable.id)
        self.login(account=user, nexturl="inv/recv_process/%s" % recv_id)

        db.commit()  # Close transaction - otherwise we get a cached response

        query = (iitable.site_id == site_id)
        after = db(query).select(orderby=iitable.id)
        # Find the differences between the before and the after
        changes = []
        for a_rec in after:
            found = False
            for b_rec in before:
                if a_rec.id == b_rec.id:
                    if a_rec.quantity != b_rec.quantity:
                        changes.append((a_rec.item_id, a_rec.item_pack_id,
                                        a_rec.quantity - b_rec.quantity))
                    found = True
                    break
            if not found:
                changes.append(
                    (a_rec.item_id, a_rec.item_pack_id, a_rec.quantity))
        # changes now contains the list of changed or new records
        # these should match the records received
        # first check are the lengths the same?
        self.assertTrue(
            len(data) == len(changes),
            "The number of changed inventory items (%s) doesn't match the number of items received  (%s)."
            % (len(changes), len(data)))
        for line in data:
            rec = line["record"]
            found = False
            for change in changes:
                if rec.inv_track_item.item_id == change[0] and \
                rec.inv_track_item.item_pack_id == change[1] and \
                rec.inv_track_item.quantity == change[2]:
                    found = True
                    break
            if found:
                s3_debug("%s accounted for." % line["text"])
            else:
                s3_debug("%s not accounted for." % line["text"])
Exemplo n.º 6
0
def dt_filter(search_string=" ", forceClear=True, quiet=True):
    """
        Filter the dataTable
    """

    if forceClear:
        if not dt_filter(forceClear=False, quiet=quiet):
            return False
    config = current.test_config
    browser = config.browser

    sleep_limit = 10
    elem = browser.find_element_by_css_selector('label > input[type="text"]')
    elem.clear()
    elem.send_keys(search_string)

    time.sleep(1)  # give time for the list_processing element to appear
    waiting_elem = browser.find_element_by_id("list_processing")
    sleep_time = 0
    while (waiting_elem.value_of_css_property("visibility") == "visible"):
        time.sleep(1)
        sleep_time += 1
        if sleep_time > sleep_limit:
            if not quiet:
                s3_debug("DataTable filter didn't respond within %d seconds" %
                         sleep_limit)
            return False
    return True
Exemplo n.º 7
0
 def helper_inv_track_send_item(self, user, send_id, data, removed=True):
     """
         Helper method to add a track item to the inv_send with the
         given send_id by the given user
     """
     try:
         add_btn = self.browser.find_element_by_id("show-add-btn")
         if add_btn.is_displayed():
             add_btn.click()
     except:
         pass
     self.login(account=user, nexturl="inv/send/%s/track_item" % send_id)
     table = "inv_track_item"
     result = self.create(table, data, dbcallback=self.dbcallback_getStockLevels)
     # Get the last record in the before & after
     # this will give the stock record which has been added to the end by
     # the getStockLevels callback
     if removed:
         qnty = 0
         for line in data:
             if line[0] == "quantity":
                 qnty = float(line[1])
                 break
         stock_before = result["before"].records[len(result["before"]) - 1].quantity
         stock_after = result["after"].records[len(result["after"]) - 1].quantity
         stock_shipped = qnty
         self.assertTrue(
             stock_before - stock_after == stock_shipped,
             "Warehouse stock not properly adjusted, was %s should be %s but is recorded as %s"
             % (stock_before, stock_after, stock_before - stock_shipped),
         )
         s3_debug("Stock level before %s, stock level after %s" % (stock_before, stock_after))
     return result
Exemplo n.º 8
0
def dt_find(search = "",
            row = None,
            column = None,
            tableID = "list",
            first = False,
           ):
    """ Find the cells where search is found in the dataTable """
    # 'todo need to fix the searching on numbers
    config = current.test_config
    browser = config.browser

    # Calculate the rows that need to be navigated along to find the search string
    colList = []
    rowList = []
    if row == None:
        r = 1
        while True:
            tr =  ".//*[@id='%s']/tbody/tr[%s]" % (tableID, r)
            try:
                elem = browser.find_element_by_xpath(tr)
                rowList.append(r)
                r += 1
            except:
                break
    elif isinstance(row, int):
        rowList = [row]
    else:
        rowList = row
    # Calculate the columns that need to be navigated down to find the search string
    if column == None:
        c = 1
        while True:
            td = ".//*[@id='%s']/tbody/tr[1]/td[%s]" % (tableID, c)
            try:
                elem = browser.find_element_by_xpath(td)
                colList.append(c)
                c += 1
            except:
                break
    elif isinstance(column, int):
        colList = [column]
    else:
        colList = column
    s3_debug("rows %s, columns %s" % (rowList, colList))
    # Now try and find a match
    result = []
    for r in rowList:
        for c in colList:
            td = ".//*[@id='%s']/tbody/tr[%s]/td[%s]" % (tableID, r, c)
            try:
                elem = browser.find_element_by_xpath(td)
                s3_debug("got %s, needle %s" % (elem.text, search))
                if elem.text == search:
                    if first:
                        return (r, c)
                    else:
                        result.append((r, c))
            except:
                pass
    return result
Exemplo n.º 9
0
def dt_links(row=1, tableID="list", quiet=True):
    """ Returns a list of links in the given row of the dataTable """

    config = current.test_config
    browser = config.browser

    links = []
    # loop through each column
    column = 1
    while True:
        td = ".//*[@id='%s']/tbody/tr[%s]/td[%s]" % (tableID, row, column)
        try:
            elem = browser.find_element_by_xpath(td)
        except:
            break
        # loop through looking for links in the cell
        cnt = 1
        while True:
            link = ".//*[@id='%s']/tbody/tr[%s]/td[%s]/a[%s]" % (tableID, row,
                                                                 column, cnt)
            try:
                elem = browser.find_element_by_xpath(link)
            except:
                break
            cnt += 1
            if not quiet:
                s3_debug("%2d) %s" % (column, elem.text))
            links.append([column, elem.text])
        column += 1
    return links
Exemplo n.º 10
0
def hrm002():

    config = current.test_config
    browser = config.browser
    driver = browser
    driver.find_element_by_link_text("Staff & Volunteers").click()
    driver.find_element_by_link_text("New Volunteer").click()
    w_autocomplete("Rom","hrm_human_resource_organisation","Romanian Food Assistance Association (Test) (RFAAT)",False)
    driver.find_element_by_id("pr_person_first_name").clear()
    driver.find_element_by_id("pr_person_first_name").send_keys("John")
    driver.find_element_by_id("pr_person_last_name").clear()
    driver.find_element_by_id("pr_person_last_name").send_keys("Thompson")
    driver.find_element_by_css_selector("img.ui-datepicker-trigger").click()
    driver.find_element_by_link_text("7").click()
    driver.find_element_by_id("pr_person_gender").send_keys("male")
    driver.find_element_by_id("pr_person_occupation").clear()
    driver.find_element_by_id("pr_person_occupation").send_keys("Social Worker")
    driver.find_element_by_id("pr_person_email").clear()
    driver.find_element_by_id("pr_person_email").send_keys("*****@*****.**")
    driver.find_element_by_id("hrm_human_resource_job_title").clear()
    driver.find_element_by_id("hrm_human_resource_job_title").send_keys("Distributor")
    driver.find_element_by_id("hrm_human_resource_start_date").click()
    driver.find_element_by_id("hrm_human_resource_start_date").clear()
    driver.find_element_by_id("hrm_human_resource_start_date").send_keys("2012-04-17")
    driver.find_element_by_id("gis_location_L0").send_keys("Romania")
    driver.find_element_by_id("gis_location_street").clear()
    driver.find_element_by_id("gis_location_street").send_keys("23 Petru St")
    driver.find_element_by_id("gis_location_L3_ac").clear()
    driver.find_element_by_id("gis_location_L3_ac").send_keys("Bucharest")
    time.sleep(5)
    driver.find_element_by_id("ui-menu-2-0").click()
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()

    s3_debug("hrm002 test: Pass")
Exemplo n.º 11
0
def dt_links(row = 1,
             tableID = "list",
             quiet = True
            ):
    """ Returns a list of links in the given row of the dataTable """
    config = current.test_config
    browser = config.browser

    links = []
    # loop through each column
    column = 1
    while True:
        td =  ".//*[@id='%s']/tbody/tr[%s]/td[%s]" % (tableID, row, column)
        try:
            elem = browser.find_element_by_xpath(td)
        except:
            break
        # loop through looking for links in the cell
        cnt = 1
        while True:
            link = ".//*[@id='%s']/tbody/tr[%s]/td[%s]/a[%s]" % (tableID, row, column, cnt)
            try:
                elem = browser.find_element_by_xpath(link)
            except:
                break
            cnt += 1
            if not quiet:
                s3_debug("%2d) %s" % (column, elem.text))
            links.append([column,elem.text])
        column += 1
    return links
Exemplo n.º 12
0
def dt_filter(search_string=" ",
              forceClear = True,
              quiet = True):
    """ filter the dataTable """
    if forceClear:
        if not dt_filter(forceClear = False,
                         quiet = quiet):
            return False
    config = current.test_config
    browser = config.browser

    sleep_limit = 10
    elem = browser.find_element_by_css_selector('label > input[type="text"]')
    elem.clear()
    elem.send_keys(search_string)

    time.sleep(1) # give time for the list_processing element to appear
    waiting_elem = browser.find_element_by_id("list_processing")
    sleep_time = 0
    while (waiting_elem.value_of_css_property("visibility") == "visible"):
        time.sleep(1)
        sleep_time += 1
        if sleep_time > sleep_limit:
            if not quiet:
                s3_debug("DataTable filter didn't respond within %d seconds" % sleep_limit)
            return False
    return True
Exemplo n.º 13
0
 def helper_inv_recv_shipment(self, user, recv_id, data):
     """
         Helper method that will receive the shipment, adding the
         totals that arrived
 
         It will get the stock in the warehouse before and then after
         and check that the stock levels have been properly increased
     """
     s3db = current.s3db
     db = current.db
     rvtable = s3db.inv_recv
     iitable = s3db.inv_inv_item
     # First get the site_id
     query = rvtable.id == recv_id
     record = db(query).select(rvtable.site_id, limitby=(0, 1)).first()
     site_id = record.site_id
     # Now get all the inventory items for the site
     query = iitable.site_id == site_id
     before = db(query).select(orderby=iitable.id)
     self.login(account=user, nexturl="inv/recv_process/%s" % recv_id)
     query = iitable.site_id == site_id
     after = db(query).select(orderby=iitable.id)
     # Find the differences between the before and the after
     changes = []
     for a_rec in after:
         found = False
         for b_rec in before:
             if a_rec.id == b_rec.id:
                 if a_rec.quantity != b_rec.quantity:
                     changes.append((a_rec.item_id, a_rec.item_pack_id, a_rec.quantity - b_rec.quantity))
             found = True
             break
         if not found:
             changes.append((a_rec.item_id, a_rec.item_pack_id, a_rec.quantity))
     # changes now contains the list of changed or new records
     # these should match the records received
     # first check are the lengths the same?
     self.assertTrue(
         len(data) == len(changes),
         "The number of changed inventory items (%s) doesn't match the number of items received  (%s)."
         % (len(changes), len(data)),
     )
     for line in data:
         rec = line["record"]
         found = False
         for change in changes:
             if (
                 rec.inv_track_item.item_id == change[0]
                 and rec.inv_track_item.item_pack_id == change[1]
                 and rec.inv_track_item.quantity == change[2]
             ):
                 found = True
                 break
         if found:
             s3_debug("%s accounted for." % line["text"])
         else:
             s3_debug("%s not accounted for." % line["text"])
Exemplo n.º 14
0
 def helper_inv_send(self, user, data):
     """
         Helper method to add a inv_send record by the given user
     """
     self.login(account=user, nexturl="inv/send/create")
     table = "inv_send"
     result = self.create(table, data)
     s3_debug("WB reference: %s" % self.helper_inv_send_get_ref(result))
     return result
Exemplo n.º 15
0
 def helper_inv_send(self, user, data):
     """
         Helper method to add a inv_send record by the given user
     """
     self.login(account=user, nexturl="inv/send/create")
     table = "inv_send"
     result = self.create(table, data)
     s3_debug("WB reference: %s" % self.helper_inv_send_get_ref(result))
     return result
Exemplo n.º 16
0
Arquivo: auth.py Projeto: AnithaT/eden
def login(account="normal", nexturl=None):
    """ Login to the system """

    config = current.test_config
    browser = config.browser

    if isinstance(account,(list,tuple)):
        email = account[0]
        password = account[1]
    if account == "normal":
        email = "*****@*****.**"
        password = "******"
    elif account == "admin":
        email = "*****@*****.**"
        password = "******"
    elif isinstance(account, (tuple,list)) and len(account) == 2:
        email = account[0]
        password = account[1]
    else:
        raise NotImplementedError

    # If the user is already logged in no need to do anything so return
    if browser.page_source.find("<a id=\"auth_menu_email\">%s</a>" % email) > 0:
        # if the url is different then move to the new url
        if not browser.current_url.endswith(nexturl):
            url = "%s/%s" % (config.url, nexturl)
            browser.get(url)
        return

    if nexturl:
        url = "%s/default/user/login?_next=%s" % (config.url, nexturl)
    else:
        url = "%s/default/user/login" % config.url
    browser.get(url)


    # Login
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Login')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        s3_debug("Login failed.. so registering account")
        # Try registering
        register(account)
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 17
0
def hrm003():
    
    config = current.test_config
    browser = config.browser
    driver = browser
    
    driver.find_element_by_link_text("Staff & Volunteers").click()
    driver.find_element_by_link_text("New Training Course").click()
    driver.find_element_by_id("hrm_course_name").click()
    driver.find_element_by_id("hrm_course_name").clear()
    driver.find_element_by_id("hrm_course_name").send_keys("Emergency First Aid")
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    driver.find_element_by_link_text("Home").click()
    s3_debug("hrm003 test: Pass")
Exemplo n.º 18
0
def login(account="normal", nexturl=None):
    """ Login to the system """

    config = current.test_config
    browser = config.browser
    data = current.data["auth"]

    if account in data:
        email = data[account]["email"]
        password = data[account]["password"]
    elif isinstance(account, (tuple, list)):
        email = account[0]
        password = account[1]
    else:
        raise NotImplementedError

    # If the user is already logged in no need to do anything so return
    if browser.page_source != None and \
       browser.page_source.find("<a id=\"auth_menu_email\">%s</a>" % email) > 0:
        # If the URL is different then move to the new URL
        if not browser.current_url.endswith(nexturl):
            url = "%s/%s" % (config.url, nexturl)
            browser.get(url)
        return

    if nexturl:
        url = "%s/default/user/login?_next=/%s/%s" % \
            (config.url, current.request.application, nexturl)
    else:
        url = "%s/default/user/login" % config.url
    browser.get(url)

    # Login
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Login')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        s3_debug("Login failed.. so registering account")
        # Try registering
        register(account)
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 19
0
def dt_row_cnt(check=(), quiet=True, utObj=None):
    """
        return the rows that are being displayed and the total rows in the dataTable
    """

    config = current.test_config
    browser = config.browser

    elem = browser.find_element_by_id("list_info")
    details = elem.text
    if not quiet:
        s3_debug(details)
    words = details.split()
    start = int(words[1])
    end = int(words[3])
    length = int(words[5])
    filtered = None
    if len(words) > 10:
        filtered = int(words[9])
    if check != ():
        if len(check) == 3:
            expected = "Showing %d to %d of %d entries" % check
            actual = "Showing %d to %d of %d entries" % (start, end, length)
            msg = "Expected result of '%s' doesn't equal '%s'" % (expected,
                                                                  actual)
            if utObj != None:
                utObj.assertEqual((start, end, length) == check, msg)
            else:
                assert (start, end, length) == check, msg
        elif len(check) == 4:
            expected = "Showing %d to %d of %d entries (filtered from %d total entries)" % check
            if filtered:
                actual = "Showing %d to %d of %d entries (filtered from %d total entries)" % (
                    start, end, length, filtered)
            else:
                actual = "Showing %d to %d of %d entries" % (start, end,
                                                             length)
            msg = "Expected result of '%s' doesn't equal '%s'" % (expected,
                                                                  actual)
            if utObj != None:
                utObj.assertEqual((start, end, length) == check, msg)
            else:
                assert (start, end, length, filtered) == check, msg
    if len(words) > 10:
        return (start, end, length, filtered)
    else:
        return (start, end, length)
Exemplo n.º 20
0
def hrm007():

    config = current.test_config
    browser = config.browser
    driver = browser

    driver.find_element_by_link_text("Warehouse").click()
    driver.find_element_by_link_text("List All").click()
    driver.find_element_by_link_text("Open").click()
    driver.find_element_by_link_text("Staff").click()
    driver.find_element_by_id("select_from_registry").click()
    w_autocomplete("Fel","hrm_human_resource_person","Felix  Ximenes",False)
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    driver.find_element_by_css_selector("span.S3menulogo").click()
    driver.find_element_by_link_text("Home").click()

    s3_debug("hrm007 test: Pass")
Exemplo n.º 21
0
def hrm006():

    config = current.test_config
    browser = config.browser
    driver = browser

    driver.find_element_by_xpath("//div[@id='facility_box']/a[4]/div").click()
    driver.find_element_by_xpath("(//a[contains(text(),'Open')])[3]").click()
    driver.find_element_by_link_text("Staff").click()
    driver.find_element_by_id("select_from_registry").click()
    driver.find_element_by_id("dummy_hrm_human_resource_person_id").clear()
    w_autocomplete("Corn","hrm_human_resource_person","Cornelio  da Cunha",False)
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    driver.find_element_by_css_selector("span.S3menulogo").click()
    driver.find_element_by_link_text("Home").click()

    s3_debug("hrm006 test: Pass")
Exemplo n.º 22
0
def register(account="normal"):
    """ Register on the system """

    config = current.test_config
    browser = config.browser

    # Load homepage
    homepage()

    if account == "normal":
        first_name = "Test"
        last_name = "User"
        email = "*****@*****.**"
    elif account == "admin":
        first_name = "Admin"
        last_name = "User"
        email = "*****@*****.**"
    else:
        raise NotImplementedError
    password = "******"

    # Register user
    elem = browser.find_element_by_id("auth_user_first_name")
    elem.send_keys(first_name)
    elem = browser.find_element_by_id("auth_user_last_name")
    elem.send_keys(last_name)
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_id("auth_user_password_two")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Register')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        assert 0, "Registration unsuccesful"
    else:
        s3_debug(elem.text)
        return True

# END =========================================================================
Exemplo n.º 23
0
    def send(self, user, data):
        """
            @case: INV
            @description: Functions which runs specific workflows for Inventory tes
            
            @TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE
            @Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing
        """
        print "\n"
        """
            Helper method to add a inv_send record by the given user
        """

        self.login(account=user, nexturl="inv/send/create")
        table = "inv_send"
        result = self.create(table, data)
        s3_debug("WB reference: %s" % self.send_get_ref(result))
        return result
Exemplo n.º 24
0
def hrm005():

    config = current.test_config
    browser = config.browser
    driver = browser
    driver.find_element_by_link_text("Organizations").click()
    driver.find_element_by_link_text("List All").click()
    driver.find_element_by_link_text("Open").click()
    driver.find_element_by_xpath("(//a[contains(text(),'Staff & Volunteers')])[2]").click()
    driver.find_element_by_id("pr_person_first_name").send_keys("Herculano")
    driver.find_element_by_id("pr_person_last_name").send_keys("Hugh")
    driver.find_element_by_id("pr_person_date_of_birth").send_keys("1968-10-18")
    driver.find_element_by_id("pr_person_gender").send_keys("male")
    driver.find_element_by_id("pr_person_email").send_keys("*****@*****.**")
    driver.find_element_by_id("hrm_human_resource_job_title").send_keys("Staff")
    driver.find_element_by_css_selector('input[type="submit"]').click()

    s3_debug("hrm005 test: Pass")
Exemplo n.º 25
0
    def helper_inv_send(self, user, data):
        """
            @case: INV
            @description: Functions which runs specific workflows for Inventory tes
            
            @TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE
            @Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing
        """
        print "\n"

        """
            Helper method to add a inv_send record by the given user
        """
        self.login(account=user, nexturl="inv/send/create")
        table = "inv_send"
        result = self.create(table, data)
        s3_debug("WB reference: %s" % self.helper_inv_send_get_ref(result))
        return result
Exemplo n.º 26
0
def register(account="normal"):
    """ Register on the system """

    config = current.test_config
    browser = config.browser
    data = current.data["auth"]

    if account in data:
        email = data[account]["email"]
        first_name = data[account]["first_name"]
        last_name = data[account]["last_name"]
        password = data[account]["password"]
    else:
        raise NotImplementedError

    # Load homepage
    homepage()

    # Register user
    elem = browser.find_element_by_id("auth_user_first_name")
    elem.send_keys(first_name)
    elem = browser.find_element_by_id("auth_user_last_name")
    elem.send_keys(last_name)
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_id("auth_user_password_two")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Register')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        assert 0, "Registration unsuccesful"
    else:
        s3_debug(elem.text)
        return True

# END =========================================================================
Exemplo n.º 27
0
def register(account="normal"):
    """ Register on the system """

    config = current.test_config
    browser = config.browser
    data = current.data["auth"]

    if account in data:
        email = data[account]["email"]
        first_name = data[account]["first_name"]
        last_name = data[account]["last_name"]
        password = data[account]["password"]
    else:
        raise NotImplementedError

    # Load homepage
    homepage()

    # Register user
    elem = browser.find_element_by_id("auth_user_first_name")
    elem.send_keys(first_name)
    elem = browser.find_element_by_id("auth_user_last_name")
    elem.send_keys(last_name)
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_id("auth_user_password_two")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Register')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        assert 0, "Registration unsuccesful"
    else:
        s3_debug(elem.text)
        return True

# END =========================================================================
Exemplo n.º 28
0
def proj001():
    config = current.test_config
    browser = config.browser
    driver = browser

    # driver.find_element_by_xpath("//a[@href='/eden/project/index']").click()
    # driver.find_element_by_xpath("//a[@href='/eden/project/project/create']").click()

    #homepage()
    login()

    driver.find_element_by_link_text("Projects").click()
    driver.find_element_by_link_text("Add New Project").click()
    driver.find_element_by_name("name").click()
    # driver.find_element_by_id("hrm_course_name").clear()
    driver.find_element_by_name("name").send_keys("My Test Project")
    driver.find_element_by_name("name").submit()
    # driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    # driver.find_element_by_link_text("Home").click()
    s3_debug("proj001 test: Pass")
Exemplo n.º 29
0
def proj001():
    config = current.test_config
    browser = config.browser
    driver = browser

    # driver.find_element_by_xpath("//a[@href='/eden/project/index']").click()
    # driver.find_element_by_xpath("//a[@href='/eden/project/project/create']").click()

    #homepage()
    login()

    driver.find_element_by_link_text("Projects").click()
    driver.find_element_by_link_text("Add New Project").click()
    driver.find_element_by_name("name").click()
    # driver.find_element_by_id("hrm_course_name").clear()
    driver.find_element_by_name("name").send_keys("My Test Project")
    driver.find_element_by_name("name").submit()
    # driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    # driver.find_element_by_link_text("Home").click()
    s3_debug("proj001 test: Pass")
Exemplo n.º 30
0
def hrm004():

    config = current.test_config
    browser = config.browser
    driver = browser
    driver.find_element_by_link_text("Staff & Volunteers").click()
    driver.find_element_by_link_text("New Training Event").click()
    driver.find_element_by_id("hrm_training_event_course_id").send_keys("Emergency First Aid")
    w_autocomplete("buch","hrm_training_event_site","Bucharest RFAAT Centre (Test) (Office)",False)
    driver.find_element_by_id("hrm_training_event_start_date").send_keys("2012-04-11")
    driver.find_element_by_id("hrm_training_event_end_date").send_keys("2012-04-12")
    driver.find_element_by_id("hrm_training_event_hours").send_keys("16")
    driver.find_element_by_id("hrm_training_event_comments").clear()
    driver.find_element_by_id("hrm_training_event_comments").send_keys("test")
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    w_autocomplete("Rob","hrm_training_person","Robert James Lemon",False)
    driver.find_element_by_id("hrm_training_comments").send_keys("test")
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    driver.find_element_by_link_text("Home").click()
    
    s3_debug("hrm004 test: Pass")
Exemplo n.º 31
0
def login(account="normal"):
    """ Login to the system """

    config = current.test_config
    browser = config.browser

    url = "%s/default/user/login" % config.url
    browser.get(url)

    if account == "normal":
        email = "*****@*****.**"
        password = "******"
    elif account == "admin":
        email = "*****@*****.**"
        password = "******"
    else:
        raise NotImplementedError

    # Login
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Login')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        s3_debug("Login failed")
        # Try registering
        register(account)
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 32
0
def staff():
    """ Tests for Staff """

    config = current.test_config
    browser = config.browser

    # Logout
    logout()

    # Open HRM module
    url = "%s/hrm" % config.url
    browser.get(url)

    # Check no unauthenticated access
    try:
        elem = browser.find_element_by_xpath("//div[@class='error']")
    except NoSuchElementException:
        if "Staff" in browser.title:
            assert 0, "HRM accessible to unauthenticated users!"
        else:
            raise RuntimeError
    else:
        s3_debug(elem.text)

    # Login
    login()

    # Open HRM module
    browser.get(url)

    # Check authenticated access
    if "Staff" not in browser.title:
        assert 0, "HRM inaccessible to authenticated user!"

    # Create a Staff member
    _create()
Exemplo n.º 33
0
def hrm001():
    
    config = current.test_config
    browser = config.browser
    driver = browser
    driver.find_element_by_link_text("Staff & Volunteers").click()
    driver.find_element_by_link_text("New Staff Member").click()
    w_autocomplete("Rom","hrm_human_resource_organisation","Romanian Food Assistance Association (Test) (RFAAT)",False)
    driver.find_element_by_id("pr_person_first_name").clear()
    driver.find_element_by_id("pr_person_first_name").send_keys("Robert")
    driver.find_element_by_id("pr_person_middle_name").clear()
    driver.find_element_by_id("pr_person_middle_name").send_keys("James")
    driver.find_element_by_id("pr_person_last_name").clear()
    driver.find_element_by_id("pr_person_last_name").send_keys("Lemon")
    driver.find_element_by_id("pr_person_date_of_birth").click()
    driver.find_element_by_id("pr_person_date_of_birth").clear()
    driver.find_element_by_id("pr_person_date_of_birth").send_keys("1980-10-14")
    driver.find_element_by_id("pr_person_gender").click()
    driver.find_element_by_id("pr_person_gender").send_keys("male")
    driver.find_element_by_id("pr_person_occupation").clear()
    driver.find_element_by_id("pr_person_occupation").send_keys("Social Worker")
    driver.find_element_by_id("pr_person_email").clear()
    driver.find_element_by_id("pr_person_email").send_keys("*****@*****.**")
    driver.find_element_by_id("hrm_human_resource_job_title").clear()
    driver.find_element_by_id("hrm_human_resource_job_title").send_keys("Social Worker")
    driver.find_element_by_id("hrm_human_resource_start_date").click()
    driver.find_element_by_id("hrm_human_resource_start_date").clear()
    driver.find_element_by_id("hrm_human_resource_start_date").send_keys("2012-02-02")
    driver.find_element_by_css_selector("#hrm_human_resource_start_date__row > td").click()
    driver.find_element_by_id("hrm_human_resource_end_date").click()
    driver.find_element_by_id("hrm_human_resource_end_date").clear()
    driver.find_element_by_id("hrm_human_resource_end_date").send_keys("2015-03-02")
    w_autocomplete("Buch","hrm_human_resource_site","Bucharest RFAAT Centre (Test) (Office)",False)
    driver.find_element_by_css_selector("input[type=\"submit\"]").click()
    
    s3_debug("hrm001 test: Pass")
Exemplo n.º 34
0
    def confirm_received_shipment(self, user, send_id):
        """
            Helper method to confirm that a shipment has been received
            outside of the system. This means that the items in the
            shipment will not be recorded as being at a site but
            the status of the shipment will be modified.
        """

        db = current.db
        s3db = current.s3db
        stable = s3db.inv_send
        ititable = s3db.inv_track_item
        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status,
                      limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 2, "Shipment is not status sent")
        s3_debug("Shipment status is: preparing")
        for rec in item_records:
            self.assertTrue(rec.status == 2, "Shipment item is not status sent")
        s3_debug("Shipment items are all of status: sent")

        # Now send the shipment on its way
        self.login(account=user, nexturl="inv/send/%s?received=True" % send_id)

        db.commit() # Close transaction - otherwise we get a cached response

        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status,
                      limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 1, "Shipment is not status received")
        s3_debug("Shipment status is: sent")
        for rec in item_records:
            self.assertTrue(rec.status == 4, "Shipment item is not status arrived")
        s3_debug("Shipment items are all of status: arrived")
Exemplo n.º 35
0
    def confirm_received_shipment(self, user, send_id):
        """
            Helper method to confirm that a shipment has been received
            outside of the system. This means that the items in the
            shipment will not be recorded as being at a site but
            the status of the shipment will be modified.
        """

        db = current.db
        s3db = current.s3db
        stable = s3db.inv_send
        ititable = s3db.inv_track_item
        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status, limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 2, "Shipment is not status sent")
        s3_debug("Shipment status is: preparing")
        for rec in item_records:
            self.assertTrue(rec.status == 2,
                            "Shipment item is not status sent")
        s3_debug("Shipment items are all of status: sent")

        # Now send the shipment on its way
        self.login(account=user, nexturl="inv/send/%s?received=True" % send_id)

        db.commit()  # Close transaction - otherwise we get a cached response

        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status, limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 1, "Shipment is not status received")
        s3_debug("Shipment status is: sent")
        for rec in item_records:
            self.assertTrue(rec.status == 4,
                            "Shipment item is not status arrived")
        s3_debug("Shipment items are all of status: arrived")
Exemplo n.º 36
0
    def send_shipment(self, user, send_id):
        """
            Helper method to send a shipment with id of send_id
        """

        db = current.db
        s3db = current.s3db
        stable = s3db.inv_send
        ititable = s3db.inv_track_item
        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status, limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 0, "Shipment is not status preparing")
        s3_debug("Shipment status is: preparing")
        for rec in item_records:
            self.assertTrue(rec.status == 1,
                            "Shipment item is not status preparing")
        s3_debug("Shipment items are all of status: preparing")

        # Now send the shipment on its way
        self.login(account=user, nexturl="inv/send_process/%s" % send_id)

        db.commit()  # Close transaction - otherwise we get a cached response

        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status, limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 2, "Shipment is not status sent")
        s3_debug("Shipment status is: sent")
        for rec in item_records:
            self.assertTrue(rec.status == 2,
                            "Shipment item is not status sent")
        s3_debug("Shipment items are all of status: sent")
Exemplo n.º 37
0
    def send_shipment(self, user, send_id):
        """
            Helper method to send a shipment with id of send_id
        """

        db = current.db
        s3db = current.s3db
        stable = s3db.inv_send
        ititable = s3db.inv_track_item
        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status,
                      limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 0, "Shipment is not status preparing")
        s3_debug("Shipment status is: preparing")
        for rec in item_records:
            self.assertTrue(rec.status == 1, "Shipment item is not status preparing")
        s3_debug("Shipment items are all of status: preparing")

        # Now send the shipment on its way
        self.login(account=user, nexturl="inv/send_process/%s" % send_id)

        db.commit() # Close transaction - otherwise we get a cached response

        # Get the current status
        query = (stable.id == send_id)
        record = db(query).select(stable.status,
                                  limitby=(0, 1)).first()
        send_status = record.status
        query = (ititable.send_id == send_id)
        item_records = db(query).select(ititable.status)
        # check that the status is correct
        self.assertTrue(send_status == 2, "Shipment is not status sent")
        s3_debug("Shipment status is: sent")
        for rec in item_records:
            self.assertTrue(rec.status == 2, "Shipment item is not status sent")
        s3_debug("Shipment items are all of status: sent")
Exemplo n.º 38
0
def login(account="normal"):
    """ Login to the system """

    config = current.test_config
    browser = config.browser

    # Load homepage
    homepage()

    if account == "normal":
        email = "*****@*****.**"
    elif account == "admin":
        email = "*****@*****.**"
    else:
        raise NotImplementedError
    password = "******"

    try:
        elem = browser.find_element_by_id("auth_menu_email")
    except NoSuchElementException:
        pass
    else:
        if elem.text == email:
            s3_debug("Logged-in already")
            return True
        else:
            # Logout of any existing user
            logout()

    # Login
    elem = browser.find_element_by_id("auth_menu_login")
    elem.click()
    elem = browser.find_element_by_id("auth_user_email")
    elem.send_keys(email)
    elem = browser.find_element_by_id("auth_user_password")
    elem.send_keys(password)
    elem = browser.find_element_by_xpath("//input[contains(@value,'Login')]")
    elem.click()

    # Check the result
    try:
        elem = browser.find_element_by_xpath("//div[@class='confirmation']")
    except NoSuchElementException:
        s3_debug("Login failed")
        # Try registering
        register(account)
    else:
        s3_debug(elem.text)
        return True
Exemplo n.º 39
0
        globals()[args["class"]])

elif args["suite"] == "smoke":
    # Run Smoke tests
    try:
        from tests.smoke import *
        broken_links = BrokenLinkTest()
        broken_links.setReportOnly(args["smoke_report"])
        broken_links.setDepth(args["link_depth"])
        broken_links.setThreshold(args["threshold"])
        broken_links.setUser(args["user_password"])
        suite = unittest.TestSuite()
        suite.addTest(broken_links)
    except NameError as msg:
        from s3 import s3_debug
        s3_debug("%s, unable to run the smoke tests." % msg)
        pass

elif args["suite"] == "roles":
    # Run Roles tests
    from tests.roles.test_roles import *
    suite = test_roles()

elif args["suite"] == "complete":
    # Run all Selenium Tests & Smoke Tests
    browser = config.browser = active_driver()
    browser.implicitly_wait(config.timeout)
    browser_open = True
    suite = loadAllTests()
    try:
        from tests.smoke import *
Exemplo n.º 40
0
    def __call__(self):
        """ Main entry point, configuration """

        logged_in = current.auth.s3_logged_in()
        if logged_in:
            fn = "alert"
        else:
            fn = "public"

        T = current.T
        s3db = current.s3db
        request = current.request

        output = {}

        # Map
        ftable = s3db.gis_layer_feature
        query = (ftable.controller == "cap") & \
                (ftable.function == fn)
        layer = current.db(query).select(ftable.layer_id,
                                         limitby=(0, 1)
                                         ).first()
        try:
            layer_id = layer.layer_id
        except:
            from s3 import s3_debug
            s3_debug("Cannot find Layer for Map")
            layer_id = None

        feature_resources = [{"name"      : T("Alerts"),
                              "id"        : "search_results",
                              "layer_id"  : layer_id,
                              "tablename" : "cap_alert",
                              "url"       : URL(c="cap", f=fn,
                                                extension="geojson"),
                              # We activate in callback after ensuring URL is updated for current filter status
                              "active"    : False,
                              }]

        _map = current.gis.show_map(callback='''S3.search.s3map()''',
                                    catalogue_layers=True,
                                    collapsed=True,
                                    feature_resources=feature_resources,
                                    save=False,
                                    )
        output["_map"] = _map

        # Filterable List of Alerts
        # - most recent first
        resource = s3db.resource("cap_alert")
        # Don't show Templates
        resource.add_filter(FS("is_template") == False)
        if not logged_in:
            # Only show Public Alerts
            resource.add_filter(FS("scope") == "Public")
        # Only show Alerts which haven't expired
        #resource.add_filter(FS("info.expires") >= request.utcnow)
        list_id = "cap_alert_datalist"
        list_fields = ["info.headline",
                       "area.name",
                       "info.description",
                       "info.sender_name",
                       ]
        # Order with most recent Alert first
        orderby = "cap_info.expires desc"
        datalist, numrows, ids = resource.datalist(fields = list_fields,
                                                   #start = None,
                                                   limit = 5,
                                                   list_id = list_id,
                                                   orderby = orderby,
                                                   layout = s3db.cap_alert_list_layout
                                                   )
        ajax_url = URL(c="cap", f=fn, args="datalist.dl", vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl = ajax_url,
                                        pagesize = 5
                                        )

        # @ToDo: Options are currently built from the full-set rather than the filtered set
        filter_widgets = [#S3LocationFilter("location.location_id",
                          #                 label=T("Location"),
                          #                 levels=("L0",),
                          #                 widget="multiselect",
                          #                 ),
                          S3OptionsFilter("info.event_type_id",
                                          label=T("Alert Type"),
                                          ),
                          S3DateFilter("info.expires",
                                       label = "",
                                       #label=T("Expiry Date"),
                                       hide_time=True,
                                       ),
                          ]
        filter_form = S3FilterForm(filter_widgets,
                                   ajax=True,
                                   submit=True,
                                   url=ajax_url,
                                   )
        output["alert_filter_form"] = filter_form.html(resource, request.get_vars, list_id)

        # Filterable News Feed
        # - most recent first
        resource = s3db.resource("cms_post")
        # Only show News posts (differentiate from e.g. online user guide)
        resource.add_filter(FS("series_id$name") == "News")
        list_id = "cms_post_datalist"
        list_fields = [#"series_id",
                       "location_id",
                       "date",
                       "body",
                       #"created_by",
                       #"created_by$organisation_id",
                       #"document.file",
                       ]
        # Order with most recent Post first
        orderby = "cms_post.date desc"
        datalist, numrows, ids = resource.datalist(fields = list_fields,
                                                   #start = None,
                                                   limit = 5,
                                                   list_id = list_id,
                                                   orderby = orderby,
                                                   layout = s3db.cms_post_list_layout
                                                   )
        ajax_url = URL(c="cms", f="post", args="datalist.dl", vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl = ajax_url,
                                        pagesize = 5
                                        )

        #filter_widgets = [#S3LocationFilter("location_id",
        #                  #                 label="",
        #                  #                 levels=("L0",),
        #                  #                 widget="multiselect",
        #                  #                 ),
        #                  # @ToDo: Source (Series? Tag?)
        #                  #S3OptionsFilter(),
        #                  ]
        #filter_form = S3FilterForm(filter_widgets,
        #                           ajax=True,
        #                           submit=True,
        #                           url=ajax_url,
        #                           )
        #output["news_filter_form"] = filter_form.html(resource, request.get_vars, list_id)

        # Title and view
        output["title"] = current.deployment_settings.get_system_name()
        self._view(THEME, "index.html")

        # Custom CSS
        current.response.s3.stylesheets.append("../themes/SAMBRO/style.css")

        return output
Exemplo n.º 41
0
    def test_add_logo(self):
        """
            This will open up an existing organisation and add a logo
        """

        nexturl = "org/organisation/"
        account = "admin"
        dataList = [
            {
                "org": "Afghan Red Crescent Society",
                "logo": "icrc-cl.gif"
            },
            {
                "org":
                "International Federation of Red Cross and Red Crescent Societies",
                "logo": "icrc.gif"
            },
        ]

        s3db = current.s3db
        db = current.db
        table = s3db.org_organisation
        itable = s3db.pr_image_library
        browser = self.browser
        for data in dataList:
            # Go to the organisation list page
            self.login(account=account, nexturl=nexturl)
            # Find the org in the dataTable (filter so only one is displayed)
            self.dt_filter(data["org"])
            # Open the org (the first - and only - by default)
            self.dt_action()
            # Add the logo to the org
            el = browser.find_element_by_id("org_organisation_logo")
            logo_path = os.path.join(self.config.base_dir, "private",
                                     "templates", "regression", data["logo"])
            s3_debug("Logo path: %s" % logo_path)
            el.send_keys(logo_path)
            # Now get the org id from the url before we save the form
            url = browser.current_url
            url_parts = url.split("/")
            org_id = url_parts[-2]
            # Submit the Form
            browser.find_element_by_css_selector(
                "input[type='submit']").click()
            # Check & Report the results
            confirm = True
            try:
                elem = browser.find_element_by_xpath(
                    "//div[@class='confirmation']")
                s3_debug(elem.text)
            except NoSuchElementException:
                confirm = False
            self.assertTrue(confirm == True,
                            "Unable to add a logo to %s" % data["org"])
            # Need to check that the logo has been added to the table
            query = (table.id == org_id) & (table.deleted == "F")
            record = db(query).select(limitby=(0, 1)).first()
            logo = record.logo
            self.assertTrue(
                logo, "The logo is not in the database for %s" % data["org"])
            s3_debug("logo file upload with the new file name of %s" % logo)
            # Check that the extra images are also created
            query = (itable.original_name == logo)
            extra_images = db(query).count()
            self.assertTrue(
                extra_images == 2,
                "The expected extra logos were not added to the image library")
            s3_debug("Two extra logos were created")
Exemplo n.º 42
0
    def create(self,
               tablename,
               data,
               success = True,
               dbcallback = None
              ):
        """
            Generic method to create a record from the data passed in

            @param tablename: The table where the record belongs
            @param data: The data that is to be inserted
            @param success: The expectation that this create will succeed
            @param dbcallback: Used by getRows to return extra data from
                               the database before & after the create

            This will return a dictionary of rows before and after the create
        """

        browser = self.browser
        result = {}
        id_data = []
        table = current.s3db[tablename]
        # Fill in the Form
        for details in data:
            el_id = "%s_%s" % (tablename, details[0])
            el_value = details[1]
            if len(details) == 3:
                el_type = details[2]
                if el_type == "option":
                    el = browser.find_element_by_id(el_id)
                    for option in el.find_elements_by_tag_name("option"):
                        if option.text == el_value:
                            option.click()
                            raw_value = option.get_attribute("value")
                            try:
                                raw_value = int(raw_value)
                            except:
                                pass
                            break
                elif el_type == "autocomplete":
                    raw_value = self.w_autocomplete(el_value,
                                                    el_id,
                                                   )
                elif el_type == "inv_widget":
                    raw_value = self.w_inv_item_select(el_value,
                                                       tablename,
                                                       details[0],
                                                      )
                elif el_type == "supply_widget":
                    raw_value = self.w_supply_select(el_value,
                                                     tablename,
                                                     details[0],
                                                    )
                elif el_type == "gis_location":
                    self.w_gis_location(el_value,
                                        details[0],
                                       )
                    raw_value = None
                #@ToDp: Fix this statement:
                #else:
                #    raise "Invalid element type"
                
            else:
                # Normal Input field
                el = browser.find_element_by_id(el_id)
                el.send_keys(el_value)
                raw_value = el_value

            if raw_value:
                # Use the raw value to check that the record was added succesfully
                id_data.append([details[0], raw_value])

        result["before"] = self.getRows(table, id_data, dbcallback)
        # Submit the Form
        browser.find_element_by_css_selector("input[type='submit']").click()
        # Check & Report the results
        confirm = True
        try:
            elem = browser.find_element_by_xpath("//div[@class='confirmation']")
            s3_debug(elem.text)
        except NoSuchElementException:
            confirm = False
        self.assertTrue(confirm == success,
                        "Unexpected create success of %s" % confirm)
        result["after"] = self.getRows(table, id_data, dbcallback)
        successMsg = "Record added to database"
        failMsg = "Record not added to database"
        if success:
            self.assertTrue((len(result["after"]) - len(result["before"])) == 1,
                            failMsg)
            s3_debug(successMsg)
        else:
            self.assertTrue((len(result["after"]) == len(result["before"])),
                            successMsg)
            s3_debug(failMsg)
        return result
Exemplo n.º 43
0
    def create(self, tablename, data, success=True, dbcallback=None):
        """
            Generic method to create a record from the data passed in

            @param tablename: The table where the record belongs
            @param data: The data that is to be inserted
            @param success: The expectation that this create will succeed
            @param dbcallback: Used by getRows to return extra data from
                               the database before & after the create

            This will return a dictionary of rows before and after the create
        """

        browser = self.browser
        result = {}
        id_data = []
        table = current.s3db[tablename]
        # Fill in the Form
        for details in data:
            el_id = "%s_%s" % (tablename, details[0])
            el_value = details[1]
            if len(details) == 3:
                el_type = details[2]
                if el_type == "option":
                    el = browser.find_element_by_id(el_id)
                    for option in el.find_elements_by_tag_name("option"):
                        if option.text == el_value:
                            option.click()
                            raw_value = option.get_attribute("value")
                            try:
                                raw_value = int(raw_value)
                            except:
                                pass
                            break
                elif el_type == "autocomplete":
                    raw_value = self.w_autocomplete(
                        el_value,
                        el_id,
                    )
                elif el_type == "inv_widget":
                    raw_value = self.w_inv_item_select(
                        el_value,
                        tablename,
                        details[0],
                    )
                elif el_type == "supply_widget":
                    raw_value = self.w_supply_select(
                        el_value,
                        tablename,
                        details[0],
                    )
                elif el_type == "gis_location":
                    self.w_gis_location(
                        el_value,
                        details[0],
                    )
                    raw_value = None
                #@ToDp: Fix this statement:
                #else:
                #    raise "Invalid element type"

            else:
                # Normal Input field
                el = browser.find_element_by_id(el_id)
                el.send_keys(el_value)
                raw_value = el_value

            if raw_value:
                # Use the raw value to check that the record was added succesfully
                id_data.append([details[0], raw_value])

        result["before"] = self.getRows(table, id_data, dbcallback)
        # Submit the Form
        browser.find_element_by_css_selector("input[type='submit']").click()
        # Check & Report the results
        confirm = True
        try:
            elem = browser.find_element_by_xpath(
                "//div[@class='confirmation']")
            s3_debug(elem.text)
        except NoSuchElementException:
            confirm = False
        self.assertTrue(confirm == success,
                        "Unexpected create success of %s" % confirm)
        result["after"] = self.getRows(table, id_data, dbcallback)
        successMsg = "Record added to database"
        failMsg = "Record not added to database"
        if success:
            self.assertTrue(
                (len(result["after"]) - len(result["before"])) == 1, failMsg)
            s3_debug(successMsg)
        else:
            self.assertTrue((len(result["after"]) == len(result["before"])),
                            successMsg)
            s3_debug(failMsg)
        return result
Exemplo n.º 44
0
Arquivo: suite.py Projeto: hoamon/eden
    suite = unittest.TestLoader().loadTestsFromTestCase(globals()[args["class"]])

elif args["suite"] == "smoke":
    try:
        from tests.smoke import *

        broken_links = BrokenLinkTest()
        broken_links.setDepth(args["link_depth"])
        broken_links.setThreshold(args["threshold"])
        broken_links.setUser(args["user_password"])
        suite = unittest.TestSuite()
        suite.addTest(broken_links)
    except NameError as msg:
        from s3 import s3_debug

        s3_debug("%s, unable to run the smoke tests." % msg)
        pass

elif args["suite"] == "roles":

    from tests.roles.test_roles import *

    # suite = unittest.TestSuite()
    suite = test_roles()

    # test_role = TestRole()
    # test_role.set(org = "Org-A",
    #              user = "******",
    #              row_num = 0,
    #              method = "create",
    #              table = "org_organisation",
Exemplo n.º 45
0
    def __call__(self):
        """ Main entry point, configuration """

        logged_in = current.auth.s3_logged_in()
        if logged_in:
            fn = "alert"
        else:
            fn = "public"

        T = current.T
        s3db = current.s3db
        request = current.request

        output = {}

        # Map
        ftable = s3db.gis_layer_feature
        query = (ftable.controller == "cap") & \
                (ftable.function == fn)
        layer = current.db(query).select(ftable.layer_id,
                                         limitby=(0, 1)
                                         ).first()
        try:
            layer_id = layer.layer_id
        except:
            from s3 import s3_debug
            s3_debug("Cannot find Layer for Map")
            layer_id = None

        feature_resources = [{"name"      : T("Alerts"),
                              "id"        : "search_results",
                              "layer_id"  : layer_id,
                              "tablename" : "cap_alert",
                              "url"       : URL(c="cap", f=fn,
                                                extension="geojson"),
                              # We activate in callback after ensuring URL is updated for current filter status
                              "active"    : False,
                              }]

        _map = current.gis.show_map(callback='''S3.search.s3map()''',
                                    catalogue_layers=True,
                                    collapsed=True,
                                    feature_resources=feature_resources,
                                    save=False,
                                    search=True,
                                    toolbar=True,
                                    )
        output["_map"] = _map

        # Filterable List of Alerts
        # - most recent first
        resource = s3db.resource("cap_alert")
        # Don't show Templates
        resource.add_filter(FS("is_template") == False)
        if not logged_in:
            # Only show Public Alerts
            resource.add_filter(FS("scope") == "Public")
        # Only show Alerts which haven't expired
        resource.add_filter(FS("info.expires") >= request.utcnow)
        list_id = "cap_alert_datalist"
        list_fields = ["msg_type",
                       "info.headline",
                       "area.name",
                       #"info.description",
                       "info.sender_name",
                       "info.priority",
                       "status",
                       "scope",
                       "info.event_type_id",
                       "info.severity",
                       "info.certainty",
                       "info.urgency",
                       "sent",
                       ]
        # Order with most recent Alert first
        orderby = "cap_info.expires desc"
        datalist, numrows, ids = resource.datalist(fields = list_fields,
                                                   #start = None,
                                                   limit = None,
                                                   list_id = list_id,
                                                   orderby = orderby,
                                                   layout = s3db.cap_alert_list_layout
                                                   )
        ajax_url = URL(c="cap", f=fn, args="datalist.dl", vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl = ajax_url,
                                        pagesize = None,
                                        )

        # @ToDo: Options are currently built from the full-set rather than the filtered set
        filter_widgets = [#S3LocationFilter("location.location_id",
                          #                 label=T("Location"),
                          #                 levels=("L0",),
                          #                 widget="multiselect",
                          #                 ),
                          S3OptionsFilter("info.priority",
                                          #label=T("Priority"),
                                          ),
                          S3OptionsFilter("info.event_type_id",
                                          #label=T("Event Type"),
                                          ),
                          S3OptionsFilter("scope",
                                          #label=T("Scope"),
                                          ),
                          S3DateFilter("info.expires",
                                       label = "",
                                       #label=T("Expiry Date"),
                                       hide_time=True,
                                       ),
                          ]
        filter_form = S3FilterForm(filter_widgets,
                                   ajax=True,
                                   submit=True,
                                   url=ajax_url,
                                   )
        output["alert_filter_form"] = filter_form.html(resource, request.get_vars, list_id)

        # Filterable News Feed
        # - most recent first
        resource = s3db.resource("cms_post")
        # Only show News posts (differentiate from e.g. online user guide)
        resource.add_filter(FS("series_id$name") == "News")
        list_id = "cms_post_datalist"
        list_fields = [#"series_id",
                       "location_id",
                       "date",
                       "body",
                       #"created_by",
                       #"created_by$organisation_id",
                       #"document.file",
                       ]
        # Order with most recent Post first
        orderby = "cms_post.date desc"
        datalist, numrows, ids = resource.datalist(fields = list_fields,
                                                   #start = None,
                                                   limit = 5,
                                                   list_id = list_id,
                                                   orderby = orderby,
                                                   # @ToDo: Custom layout with more button to expand content block
                                                   layout = s3db.cms_post_list_layout
                                                   )
        ajax_url = URL(c="cms", f="post", args="datalist.dl", vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl = ajax_url,
                                        pagesize = 5
                                        )
        # Truncate body
        #from s3 import s3_trunk8
        #s3_trunk8(lines=8)

        #filter_widgets = [#S3LocationFilter("location_id",
        #                  #                 label="",
        #                  #                 levels=("L0",),
        #                  #                 widget="multiselect",
        #                  #                 ),
        #                  # @ToDo: Source (Series? Tag?)
        #                  #S3OptionsFilter(),
        #                  ]
        #filter_form = S3FilterForm(filter_widgets,
        #                           ajax=True,
        #                           submit=True,
        #                           url=ajax_url,
        #                           )
        #output["news_filter_form"] = filter_form.html(resource, request.get_vars, list_id)

        # Title and view
        output["title"] = current.deployment_settings.get_system_name()
        self._view(THEME, "index.html")

        s3 = current.response.s3
        # Custom CSS
        s3.stylesheets.append("../themes/SAMBRO/style.css")

        # Custom JS
        s3.scripts.append("/%s/static/themes/SAMBRO/js/homepage.js" % request.application)

        return output
Exemplo n.º 46
0
    def test_add_logo(self):
        """
            This will open up an existing organisation and add a logo
        """

        nexturl = "org/organisation/"
        account = "admin"
        dataList = [
                    {"org" : "Afghan Red Crescent Society",
                     "logo" : "icrc-cl.gif"
                    },
                    {"org" : "International Federation of Red Cross and Red Crescent Societies",
                     "logo" : "icrc.gif"
                    },
                   ]

        s3db = current.s3db
        db = current.db
        table = s3db.org_organisation
        itable = s3db.pr_image_library
        browser = self.browser
        for data in dataList:
            # Go to the organisation list page
            self.login(account=account, nexturl=nexturl)
            # Find the org in the dataTable (filter so only one is displayed)
            self.dt_filter(data["org"])
            # Open the org (the first - and only - by default)
            self.dt_action()
            # Add the logo to the org
            el = browser.find_element_by_id("org_organisation_logo")
            logo_path = os.path.join(self.config.base_dir,
                                     "private", "prepopulate", "regression",
                                     data["logo"])
            s3_debug("Logo path: %s" % logo_path)
            el.send_keys(logo_path)
            # Now get the org id from the url before we save the form
            url = browser.current_url
            url_parts = url.split("/")
            org_id = url_parts[-2]
            # Submit the Form
            browser.find_element_by_css_selector("input[type='submit']").click()
            # Check & Report the results
            confirm = True
            try:
                elem = browser.find_element_by_xpath("//div[@class='confirmation']")
                s3_debug(elem.text)
            except NoSuchElementException:
                confirm = False
            self.assertTrue(confirm == True,
                            "Unable to add a logo to %s" % data["org"])
            # Need to check that the logo has been added to the table
            query = (table.id == org_id) & (table.deleted == "F")
            record = db(query).select(limitby=(0, 1)).first()
            logo = record.logo
            self.assertTrue(logo,
                            "The logo is not in the database for %s" % data["org"])
            s3_debug("logo file upload with the new file name of %s" % logo)
            # Check that the extra images are also created
            query = (itable.original_name == logo)
            extra_images = db(query).count()
            self.assertTrue(extra_images == 2,
                            "The expected extra logos were not added to the image library")
            s3_debug("Two extra logos were created")