示例#1
0
def step_impl(context, what):
    util = context.util
    card = util.find_element(
        (By.CSS_SELECTOR, "div.semantic-field-details-card .card-body"))

    stale = object()

    def check(*_):
        crumbs = card.find_elements_by_class_name("sf-breadcrumbs")
        # The check can be done so fast that we can a
        # StaleElementReferenceException. We'll just retry.
        try:
            text = crumbs[0].text if len(crumbs) > 0 else None
        except StaleElementReferenceException:
            return Result(False, stale)

        return Result(text == what, text)

    result = Condition(util, check).wait()

    if result.payload is stale:
        raise ValueError(
            "kept getting StaleElementReferenceException, somehow")

    assert_equal(result.payload, what)
示例#2
0
def step_impl(context, which, what):
    driver = context.driver
    util = context.util

    def check(*_):
        ret = driver.execute_script(
            """
        var which = arguments[0];
        var $ = jQuery;
        var $children = $("#sb-errorlist a");
        var el;
        switch (which) {
        case "first":
            el = $children[0];
            break;
        case "last":
            el = $children.last()[0];
            break;
        default:
            throw new Error("unknown which value: " + which);
        }
        return el.textContent;
        """, which)

        # Sigh... Firefox will come close but not quite, so...
        return Result(ret == what, ret)

    ret = Condition(util, check).wait().payload
    assert_equal(ret, what)
示例#3
0
def step_impl(context, existence, name):
    util = context.util

    def check(driver):
        # We must wait until the wrapper is present because the table
        # won't be ready for examination until then.
        ret = driver.execute_script(
            """
        var name = arguments[0];
        var check_for_existence = arguments[1];
        var ths = document.querySelectorAll(
            "#search-table_wrapper #search-table thead th");
        if (ths.length == 0)
            return [false, "no headings"];

        if (check_for_existence) {
            for (var i = 0, th; (th = ths[i]); ++i) {
                if (th.textContent.trim() === name)
                    return [true, undefined];
            }
            return [false, name + " is not present"];
        }

        for (var i = 0, th; (th = ths[i]); ++i) {
            if (th.textContent.trim() === name)
                return [false, name + " is present"];
        }

        return [true, undefined];
        """, name, existence == "a")

        return Result(ret[0], ret[1])

    result = Condition(util, check).wait()
    assert_true(result, result.payload)
示例#4
0
def step_impl(context, citation, not_op=None):
    def check(driver):
        ret = driver.execute_script(
            btw_util.GET_CITATION_TEXT + r"""
    var start = arguments[0];
    var not_op = arguments[1];
    var citations = document.getElementsByClassName("btw:cit");
    var cits = Array.prototype.filter.call(citations, function (cit) {
      var text = getCitationText(cit);
      return text.lastIndexOf(start, 0) === 0;
    });
    if (cits.length !== 1)
      return [false, "there should be exactly one citation"];
    var cit = cits[0];
    var parent = cit.parentNode;
    while (parent && parent.classList) {
      if (parent.classList.contains("collapse") &&
          !parent.classList.contains("show"))
        return [!not_op, "should not be in a collapsed section"];
      if (parent.classList.contains("collapsing"))
        return [false, "should not be in a section that is in the "+
                        "midst of collapsing or expanding"];
      parent = parent.parentNode;
    }
    return [not_op, "should be in a collapsed section"];
        """, citation, not_op is not None)
        return Result(ret[0], ret[1])

    result = Condition(context.util, check).wait()
    assert_true(result, result.payload)
示例#5
0
def step_impl(context):
    util = context.util

    expected = {
        u'command': u'save',
        u'data': _SCENARIO_TO_EXPECTED_DATA[context.scenario.name]
    }

    def cond(_driver):
        resp = requests.get(
            urljoin(context.local_server, "/build/ajax/save.txt"))
        text = resp.text.replace('\n***\n', '').strip()
        text = last_obj_re.sub('{', text)
        actual = json.loads(text)
        # We don't care about the version here.
        del actual["version"]
        if util.ie and u"data" in actual:
            actual[u"data"] =  \
                flip_rend_style_re.sub(ur'\2 \1',
                                       actual[u"data"])
            actual[u"data"] = \
                flip_xmlns_re.sub(ur'\2 \1',
                                  actual[u"data"])
        return Result(actual == expected, [actual, expected])

    result = Condition(util, cond).wait()

    assert_equal.__self__.maxDiff = None
    if not result:
        assert_equal(result.payload[0], result.payload[1])
示例#6
0
def step_impl(context, page):
    driver = context.driver
    parts = page.split("/")

    def check(driver):
        active = driver.execute_script("""
        var actives = document.querySelectorAll(
            "#btw-site-navigation .active>a");
        return Array.prototype.map.call(actives, function (active) {
            var ret = [];
            Array.prototype.forEach.call(active.childNodes,
            function (node) {
                if (node.nodeType === Node.TEXT_NODE)
                    ret.push(node.textContent.trim());
            });
            return ret.join('');
        });
        """)
        return Result(active == parts, [active, parts])

    result = Condition(context.util, check).wait()
    if not result:
        active, parts = result.payload
        assert_equal(active, parts)

    # We need this, otherwise the page will be reloaded too fast.
    if page == "Lexicography/New Article":
        btw_util.wait_for_editor(context.util)
示例#7
0
def step_impl(context, step, where=None):
    driver = context.driver
    util = context.util

    if step.startswith("that a typeahead"):
        element, ph = driver.execute_script("""
        var ph = document.querySelector(".p>._placeholder");
        return [ph.parentNode, ph];
        """)
        ActionChains(driver) \
            .click(ph) \
            .perform()
        # ph.click()
    elif where:
        element = driver.execute_script("""
        var title = document.querySelector("._real.title");
        var text;
        var child = title.firstChild;
        while (child && !text) {
            if (child.nodeType === Node.TEXT_NODE)
                text = child;
            child = child.nextSibling;
        }
        wed_editor.caretManager.setCaret(text, text.length);
        return title;
        """)
    else:
        element = None

    util.ctrl_equivalent_x("/")

    context.context_menu_for = element
    context.execute_steps(u"""
    When the user clicks the choice named "Test typeahead"
    """)

    def check(driver):
        ret = driver.execute_script("""
        var input = document.querySelector(
          '.wed-typeahead-popup input.tt-input');
        if (!input)
          return [false, "cannot find input element"];
        return [document.activeElement === input, "input not focused"];
        """)
        return Result(ret[0], ret[1])

    result = Condition(util, check).wait()
    assert_true(result, result.payload)

    # Move the mouse pointer out of the way. The problem is that if we leave he
    # mouse pointer where it is, then it is hovering over the completion
    # menu. This is a problem because the hover is treated as a user action,
    # and the choice under the mouse pointer is effectively selected. It did
    # not use to be a problem but a change in Selenium or Chrome made it an
    # issue. :-/
    ActionChains(driver) \
        .move_to_element(context.origin_object) \
        .perform()
示例#8
0
def step_impl(context, which):
    driver = context.driver
    util = context.util

    def check(*_):
        ret = driver.execute_script(
            """
        var which = arguments[0];
        var $ = jQuery;
        var $children = $("#sb-errorlist a");
        var el;
        switch (which) {
        case "first":
            el = $children[0];
            break;
        case "last":
            el = $children.last()[0];
            break;
        default:
            throw new Error("unknown which value: " + which);
        }
        var href = el.attributes.href.value;
        if (href[0] !== "#")
            throw new Error("unexpected link");

        var target = document.getElementById(href.slice(1));
        var scroller_rect = wed_editor.scroller.getBoundingClientRect();
        var target_rect = target.getBoundingClientRect();
        function rectToObj(rect) {
            return {top: rect.top, bottom: rect.bottom,
                    left: rect.left, right: rect.right};
        }
        return {target: rectToObj(target_rect),
                scroller: rectToObj(scroller_rect)};
        """, which)

        target = ret["target"]
        scroller = ret["scroller"]
        if target["top"] < scroller["top"]:
            return Result(False, "error marker above window")

        if target["bottom"] > scroller["bottom"]:
            return Result(False, "error marker below window")

        if target["left"] < scroller["left"]:
            return Result(False, "error marker to left of window")

        if target["right"] > scroller["right"]:
            return Result(False, "error marker to right of window")

        return Result(True, None)

    ret = Condition(util, check).wait()
    assert_true(ret, ret.payload)
示例#9
0
文件: paste.py 项目: datascouting/wed
def step_impl(context):
    def cond(driver):
        text = driver.execute_script("""
        var ps = wed_editor.dataRoot.querySelectorAll("body>p");
        var p = ps[ps.length - 1];
        return p.innerHTML;
        """)
        return Result(text == context.expected_selection_serialization, text)

    ret = Condition(context.util, cond).wait()
    assert_true(
        ret, ret.payload + " should equal " +
        context.expected_selection_serialization)
示例#10
0
def step_impl(context, what, which):
    util = context.util
    result_ix = {"first": 0, "second": 1}[which]
    result = context.default_table.get_result(result_ix)

    def find(*_):
        links = result.find_elements_by_link_text(what)
        link = links[0] if len(links) else None
        return Result(link is not None, link)

    result = Condition(util, find).wait()
    assert_true(result, "there should be a link")

    result.payload.click()
示例#11
0
def step_impl(context):
    def cond(driver):
        result = context.driver.execute_script("""
        if (wed_editor.caretManager.caret === undefined) {
          return [false, "no GUI caret"];
        }

        const caret = wed_editor.caretManager.getDataCaret(true);
        if (caret === undefined) {
          return [false, "no caret"];
        }

        let { node } = caret;
        if (node.ownerElement) {
          node = node.ownerElement;
        }
        else if (node.nodeType === Node.TEXT_NODE) {
          node = node.parentNode;
        }

        const actual = {};
        for (let ix = 0; ix < node.attributes.length; ++ix) {
          const attr = node.attributes[ix];
          actual[attr.name] = {
            ns: attr.namespaceURI === null ? "" : attr.namespaceURI,
            value: attr.value,
          }
        }

        return [true, actual];
        """)

        return Result(result[0], result[1])

    result = Condition(context.util, cond).wait()
    assert_true(result, result.payload)
    actual = result.payload

    expected = context.table.rows
    assert_equal(
        len(actual), len(expected),
        "expected {} attributes, but found {}".format(len(expected),
                                                      actual.keys()))

    for row in expected:
        name = row["name"]
        assert_true(name in actual,
                    "expected {}, but did not find it".format(name))
        attr = actual[name]
        assert_equal(attr, {"ns": row["ns"], "value": row["value"]})
示例#12
0
def step_impl(context, count):
    util = context.util

    if count == "are no files":

        def check(driver):
            ret = driver.execute_script("""
            var table = document.getElementById("files-table");
            if (!table)
                return [false, "the table is being manipulated"];
            if (table.parentNode.style.display === "none")
                return [false, "the table is hidden"];
            var td = document.querySelector("tr.files-table-empty");
            return [!td.classList.contains("ng-hide"),
                    "the empty table element is hidden"];
            """)
            return Result(ret[0], ret[1])
    elif count == "is one file":

        def check(driver):
            ret = driver.execute_script(
                """
            var count = arguments[0];
            var table = document.getElementById("files-table");
            if (!table)
                return [false, "the table is being manipulated"];
            if (table.parentNode.style.display === "none")
                return [false, "the table is hidden"];
            var td = document.querySelector("tr.files-table-empty");
            if (!td.classList.contains("ng-hide"))
                return [false, "the element for the empty list is not hidden"];
            var trs = document.querySelectorAll(
                "#files-table>tbody>tr:not(.ng-hide)");
            // We have one header row
            var data_count = trs.length - 1;
            if (data_count !== count)
                return [false, "data row count incorrect: " + data_count];
            if (!trs[data_count].classList.contains("last"))
                return [false, "last row is not present"];
            return [true, ""];
            """, 1)
            return Result(ret[0], ret[1])

    # This may be the first test in a scenario. When on SauceLabs, the
    # time it takes to load can be considerable, hence the local
    # timeout.
    with util.local_timeout(10):
        result = Condition(util, check).wait()

    assert_true(result, result.payload)
示例#13
0
def step_impl(context):
    def check(driver):
        texts = driver.execute_script("""
        var children = document.querySelectorAll(
          "div.semantic-field-details-card .sf-other-pos .sf-link");
        return Array.prototype.map.call(children, function (x) {
          return x.textContent;
        });
        """)

        return Result("FOO (None)" in texts, texts)

    result = Condition(context.util, check).wait()

    assert_true(result)
示例#14
0
def step_impl(context, where):
    util = context.util

    initial_subsenses = context.initial_subsenses_by_sense["A"]

    def check(driver):
        subsenses = btw_util.get_subsenses_for_sense(util, "A")
        if len(subsenses) != len(initial_subsenses) + 1:
            return Result(False,
                          "no new subsense was created")

        if where == "after":
            expected = {"explanation": "sense a1",
                        "head": "[brief explanation of sense a1]"}
            if subsenses[0] != expected:
                return Result(False,
                              "unexpected value for first subsense: {0} != {1}"
                              .format(subsenses[0], expected))

            expected = {"explanation": '',
                        "head": "[brief explanation of sense a2]"}
            if subsenses[1] != expected:
                return Result(
                    False,
                    "unexpected value for second subsense: {0} != {1}"
                    .format(subsenses[1], expected))
        elif where == "before":
            expected = {"explanation": '',
                        "head": "[brief explanation of sense a1]"}
            if subsenses[0] != expected:
                return Result(False,
                              "unexpected value for first subsense: {0} != {1}"
                              .format(subsenses[0], expected))

            expected = {"explanation": "sense a1",
                        "head": "[brief explanation of sense a2]"}
            if subsenses[1] != expected:
                return Result(
                    False,
                    "unexpected value for second subsense: {0} != {1}"
                    .format(subsenses[1], expected))
        else:
            raise ValueError("unexpected value for where: " + where)

        return Result(True, "")

    result = Condition(util, check).wait()
    assert_true(result, result.payload)
示例#15
0
def step_impl(context, step, where=None):
    driver = context.driver
    util = context.util

    if step.startswith("that a typeahead"):
        element, ph = driver.execute_script("""
        var ph = document.querySelector(".p>._placeholder");
        return [ph.parentNode, ph];
        """)
        ActionChains(driver) \
            .click(ph) \
            .perform()
        # ph.click()
    elif where:
        element = driver.execute_script("""
        var title = document.querySelector("._real.title");
        var text;
        var child = title.firstChild;
        while (child && !text) {
            if (child.nodeType === Node.TEXT_NODE)
                text = child;
            child = child.nextSibling;
        }
        wed_editor.caretManager.setCaret(text, text.length);
        return title;
        """)
    else:
        element = None

    util.ctrl_equivalent_x("/")

    context.context_menu_for = element
    context.execute_steps(u"""
    When the user clicks the choice named "Test typeahead"
    """)

    def check(driver):
        ret = driver.execute_script("""
        var input = document.querySelector(
          '.wed-typeahead-popup input.tt-input');
        if (!input)
          return [false, "cannot find input element"];
        return [document.activeElement === input, "input not focused"];
        """)
        return Result(ret[0], ret[1])

    result = Condition(util, check).wait()
    assert_true(result, result.payload)
def step_impl(context, fields):

    def check(driver):
        field_text = driver.execute_script(r"""
        var selector = arguments[0];
        var els = document.querySelectorAll(selector);
        return Array.prototype.map.call(els, function (x) {
          return x.textContent.trim().replace(/\s+/, ' ');
        });
        """, r".btw\:sf")

        combined = ", ".join('"{}"'.format(text) for text in field_text)
        return Result(combined == fields, combined)

    result = Condition(context.util, check).wait()
    assert_equal(result.payload, fields)
示例#17
0
def step_impl(context, count):
    # We need to remove the template, which remains undisplayed...
    if count == "one":
        count = 1
    elif count == "no":
        count = 0
    else:
        count = int(count)

    def check(driver):
        panes = get_panes(driver)
        return Result(len(panes) == count, len(panes))

    result = Condition(context.util, check).wait()

    assert_equal(result.payload, count)
示例#18
0
文件: errors.py 项目: nenadg/wed
def step_impl(context):
    driver = context.driver
    util = context.util

    def check(*_):
        top = driver.execute_script("""
        var errors = document.getElementsByClassName("wed-validation-error");
        var last = errors[errors.length - 1];
        // Get the position relative to the scroller element.
        return last.getBoundingClientRect().top -
            wed_editor._scroller.getBoundingClientRect().top;
        """)

        # Sigh... Firefox will come close but not quite, so...
        return Result(abs(top) < 5, top)

    ret = Condition(util, check).wait().payload
    assert_true(
        abs(ret) < 5, "the top should be within -5 and 5 (got: " + str(ret))
示例#19
0
    def wait_for_results(self, expected_total):
        def check(driver):
            infos = driver.find_elements_by_css_selector(
                "#" + self.cssid + " .footer-information")

            if len(infos) == 0:
                total = 0
            else:
                text = infos[0].text

                match = info_re.match(text)
                if not match:
                    return Result(False, 0)

                total = int(match.group(3))
            return Result(total == expected_total, total)

        result = Condition(self.util, check).wait()

        return result.payload
示例#20
0
def step_impl(context, lang):
    util = context.util

    # In theory the operation that we are testing here is
    # asynchronous. It should usually be fast enough so that by the
    # time we perform this test, it is already in effect but
    # hmm... delays seem to happen sometimes, so...

    def check(driver):
        test = driver.execute_script(r"""
        var $el = jQuery(".btw\\:definition .foreign:contains('prasāda')");
        if (!$el[0])
            return [false, undefined];
        return [true, $el.attr('data-wed-xml---lang-')];
        """)

        return Result(test[0], test[1])

    result = Condition(util, check).wait()
    assert_true(result)
    assert_equal(result.payload, LANG_TO_CODE[lang])
示例#21
0
def step_impl(context):
    util = context.util

    def check(driver):
        ret = driver.execute_script(r"""
        var cont =
            document.getElementsByClassName("btw:contrastive-section");
        if (cont.length !== 1)
            return [false,
                    "There is not exactly one contrastive section"];
        var nones = cont[0].querySelectorAll(
            ".btw\\:contrastive-section>*>.btw\\:none");
        if (nones.length !== 3)
            return [false, "There aren't 3 btw:none elements that " +
                           "are grand-children of " +
                           "btw:contrastive-section"];
        return [true, ''];
        """)

        return Result(ret[0], ret[1])

    result = Condition(util, check).wait()
    assert_true(result, result.payload)
示例#22
0
def step_impl(context, number, name, saved, uploaded, downloaded):
    if saved == "never been saved":
        saved = "never"
    elif saved == "been saved recently":
        saved = "recent"
    else:
        raise ValueError("unknown saved value: " + saved)

    if uploaded == "been uploaded recently":
        uploaded = "recent"
    elif uploaded == "been uploaded":
        uploaded = "not never"
    else:
        raise ValueError("unknown uploaded value: " + uploaded)

    if downloaded == "never been downloaded":
        downloaded = "never"
    elif downloaded == "been downloaded recently":
        downloaded = "recent"
    else:
        raise ValueError("unknown downloaded value: " + downloaded)

    util = context.util

    try:
        prev_file_state = context.previous_file_state[name]
    except KeyError:
        never = {"literal": "never", "seq": 0}
        prev_file_state = {
            "saved": never,
            "uploaded": never,
            "downloaded": never,
            "exists": False
        }

    def check(driver):
        file_state = get_file_state(context, name)

        def check_date(value, name):
            if value == "never":
                if file_state[name]["literal"] != "never":
                    return [False, name + " is " + file_state[name]["literal"]]
            elif value == "not never":
                if file_state[name]["literal"] == "never":
                    return [False, "never been " + name]
            elif file_state[name]["seq"] <= prev_file_state[name]["seq"]:
                return [False, "not " + name + " recently"]
            return False

        ret = check_date(saved, "saved")
        if ret:
            return Result(ret[0], ret[1])

        ret = check_date(uploaded, "uploaded")
        if ret:
            return Result(ret[0], ret[1])

        ret = check_date(downloaded, "downloaded")
        if ret:
            return Result(ret[0], ret[1])

        return Result(True, "no errors")

    result = Condition(util, check).wait()
    assert_true(result, result.payload)
示例#23
0
def step_impl(context, example, label, term=None, citation=None):

    id_selector = sanitize_id_selector(context,
                                       "#BTW-E." if example else "#BTW-S.")

    def cond(driver):
        ret = driver.execute_script(
            btw_util.GET_CITATION_TEXT + r"""
        var label = arguments[0];
        var term = arguments[1];
        var id_selector = arguments[2];
        var citation = arguments[3];
        var $ = jQuery;

        var links = Array.prototype.slice.call(document.querySelectorAll(
            ".wed-document a[href^='" + id_selector + "']")).filter(
            function (x) {
                return x.textContent.replace(/\s+/g, " ") === label; });
        if (!links[0])
            return [false, "there should be a link with text " + label];

        var target = document.getElementById(links[0].attributes["href"]
            .value.slice(1));
        if (!target)
            return [false, "there should be a target"];

        // It would be easier to inspect the data tree rather than
        // inspect the GUI tree and clean it up. However, this code needs
        // to work to test viewing articles, which has no data tree to
        // work with.

        function cleanup(node) {
            if (!node.classList.contains("head")) {
                var heads = node.getElementsByClassName("head");
                while (heads.length)
                    heads[0].parentNode.removeChild(heads[0]);
            }
            var phantom = node.getElementsByClassName("_phantom");
            while (phantom.length)
                phantom[0].parentNode.removeChild(phantom[0]);
            var decorations = node.getElementsByClassName("_decoration_text");
            while (decorations.length)
                decorations[0].parentNode.removeChild(decorations[0]);
            return node;
        }

        var test = false;
        var actual_term, desc;
        if (target.matches(".btw\\:sense")) {
            actual_term = cleanup(
                target.querySelector(".btw\\:english-term").cloneNode(true))
                .textContent;
            test = term === actual_term;
            desc = actual_term + " should match " + term;
        }
        else if (target.matches(".btw\\:subsense")) {
            actual_term = cleanup(
                 target.querySelector(".btw\\:explanation").cloneNode(true))
                 .textContent;
            test = term === actual_term;
            desc = actual_term + " should match " + term;
        }
        else if (target.matches(".btw\\:example, .btw\\:example-explained")) {
            if (term) {
                var order = { "first": 0, "second": 1, "third":2 }[term];
                var examples = document.querySelectorAll(
                    ".btw\\:example, .btw\\:example-explained");
                test = examples[order] === target;
                desc = "link should point to the " + term + " example";
            }
            else {
                var cit = target.getElementsByClassName("btw:cit")[0];
                var text = getCitationText(cit);

                test = text.lastIndexOf(citation, 0) === 0;
                desc = "link should point to the example that has a " +
                    'citation that starts with "' + citation +
                    '" but points to "' + text + '"';
            }
        }
        else
            return [false,
                    "unexpected target (tagName: " + target.tagName + ")"];

        return [test, desc];
        """, label, term, id_selector, citation)

        return Result(ret[0], ret)

    result = Condition(context.util, cond).wait()
    assert_true(result.payload[0], result.payload[1])