Example #1
0
def main(vectors):
    sys.exit(run(partial(test, vectors)))
Example #2
0
#!/usr/bin/env python3

import os
import sys


def testfunc(child):
    child.expect_exact('- User: johndoe')
    child.expect_exact('- Admin: false')
    child.expect_exact('- UID: 1000')
    child.expect_exact('- Groups:')
    child.expect_exact('  * users')
    child.expect_exact('  * wheel')
    child.expect_exact('  * audio')
    child.expect_exact('  * video')


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTTOOLS'], 'testrunner'))
    from testrunner import run
    sys.exit(run(testfunc))
Example #3
0
def testfunc(child):
    tap = get_bridge(os.environ["TAP"])

    lladdr_src = get_host_lladdr(tap)
    child.sendline("ifconfig")
    child.expect(r"HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)\s")
    hwaddr_dst = child.match.group("hwaddr").lower()
    child.expect(r"(?P<lladdr>fe80::[A-Fa-f:0-9]+)\s")
    lladdr_dst = child.match.group("lladdr").lower()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_empty_hop_by_hop_opt_wo_register)
    run(test_empty_hop_by_hop_opt_w_register)
    run(test_empty_duplicate_hop_by_hop_opt)
    run(test_empty_non_first_hop_by_hop_opt)
    run(test_empty_duplicate_non_first_hop_by_hop_opt)
    run(test_empty_routing_header_wo_register)
    run(test_empty_routing_header_w_register)
    run(test_empty_fragment_header_wo_register)
    run(test_empty_fragment_header_w_register)
    run(test_empty_dest_opt_wo_register)
    run(test_empty_dest_opt_w_register)
    # check various registrations with recommended order to validate parsing
    # (recommended order, see https://tools.ietf.org/html/rfc8200#section-4.1)
    run(test_empty_mixed1_w_hop_opt_registered)
    run(test_empty_mixed1_w_rt_hdr_registered)
    run(test_empty_mixed1_w_frag_hdr_registered)
    run(test_empty_mixed1_w_dest_opt_registered)
    # other orders SHOULD also be parsed (and since checking the order is more
    # complicated we are able to do that)
    run(test_empty_mixed2_w_hop_opt_registered)
    run(test_empty_mixed2_w_rt_hdr_registered)
    run(test_empty_mixed2_w_frag_hdr_registered)
    run(test_empty_mixed2_w_dest_opt_registered)
    print("SUCCESS")
Example #4
0
def testfunc(child):
    child.expect_exact("od_hex_dump(short_str, sizeof(short_str), OD_WIDTH_DEFAULT)")
    child.expect_exact("00000000  41  42  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), OD_WIDTH_DEFAULT)")
    child.expect_exact("00000000  FF  2C  61  FF  2E  62  63  64  65  66  67  68  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 4)")
    child.expect_exact("00000000  FF  2C  61  FF")
    child.expect_exact("00000004  2E  62  63  64")
    child.expect_exact("00000008  65  66  67  68")
    child.expect_exact("0000000C  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70")
    child.expect_exact("00000014  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 3)")
    child.expect_exact("00000000  FF  2C  61")
    child.expect_exact("00000003  FF  2E  62")
    child.expect_exact("00000006  63  64  65")
    child.expect_exact("00000009  66  67  68")
    child.expect_exact("0000000C  69  6A  6B")
    child.expect_exact("0000000F  6C  6D  6E")
    child.expect_exact("00000012  6F  70  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 8)")
    child.expect_exact("00000000  FF  2C  61  FF  2E  62  63  64")
    child.expect_exact("00000008  65  66  67  68  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70  00")

    print("All tests successful")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, timeout=1, echo=False))
Example #5
0
#!/usr/bin/env python3

# Copyright (C) 2019 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import sys
from testrunner import run
from pexpect import TIMEOUT


def testfunc(child):
    res = child.expect([TIMEOUT, "Message was not written"])
    # we actually want the timeout here. The application runs into an assertion
    # pretty quickly when failing and runs forever on success
    assert(res == 0)


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=10))
Example #6
0
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_wrong_type)
    run(test_seg_left_gt_len_addresses)
    run(test_multicast_dst)
    run(test_multicast_addr)
    run(test_multiple_addrs_of_mine_uncomp)
    run(test_forward_uncomp)
    run(test_forward_uncomp_not_first_ext_hdr)
    # compressed tests hard to implement with scapy and also covered in
    # unittests
    run(test_seq_left_0)
    run(test_time_exc)
    print("SUCCESS")
    sniffer.stop()


if __name__ == "__main__":
    if os.geteuid() != 0:
        print(
            "\x1b[1;31mThis test requires root privileges.\n"
            "It's constructing and sending Ethernet frames.\x1b[0m\n",
            file=sys.stderr)
        sys.exit(1)
    sys.exit(run(testfunc, timeout=1, echo=False))
Example #7
0
    assert uriref(n.a) == "test:x#a"
    assert uriref(n.b) == "test:x#b"


def test09():
    n = Namespace("test:x#", "a", "b", "c")
    assert uriref(n("jake")) == "test:x#jake"
    assert uriref(n("b")) == "test:x#b"

# def test10():
#       n = Namespace("test:x#", "a", "b", "c")
#       try:
#               n.jake
#       except AttributeError:
#               pass
#       else:
#               assert 0


def test11():
    n = Namespace("test:x#", "jake")
    for r in n:
        assert uriref(r) == "test:x#jake"
        break
    else:
        assert 0

if __name__ == "__main__":
    from testrunner import run
    run(globals())
Example #8
0
        return {"hi_there": "Hello, %s!" % who}

    def getdict(self):
        return dict(nested_dict=dict(a=17, b=5))

    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass


if __name__ == "__main__":
    # Instantiate a TestServer on the first free port in the specified port
    # range. Doing this inline is better than in a daemon thread: if it blows
    # up here, we'll get a traceback. If it blew up in some other thread, the
    # traceback would get eaten and we'd run the subject test program anyway.
    xmlrpcd, port = freeport(xrange(8000, 8020), lambda port: TestServer(
        ('127.0.0.1', port)))
    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["PORT"] = str(port)
    sys.exit(
        run(server=Thread(name="xmlrpc", target=xmlrpcd.serve_forever),
            *sys.argv[1:]))
Example #9
0
    data, addr = s.recvfrom(RCVBUF_LEN)
    assert(len(data) == (ZEP_DATA_HEADER_SIZE + len("Hello\0World\0") + FCS_LEN))
    assert(b"Hello\0World\0" == data[ZEP_DATA_HEADER_SIZE:-2])
    child.expect_exact("Waiting for an incoming message (use `make test`)")
    s.sendto(b"\x45\x58\x02\x01\x1a\x44\xe0\x01\xff\xdb\xde\xa6\x1a\x00\x8b" +
             b"\xfd\xae\x60\xd3\x21\xf1\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
             b"\x00\x22\x41\xdc\x02\x23\x00\x38\x30\x00\x0a\x50\x45\x5a\x00" +
             b"\x5b\x45\x00\x0a\x50\x45\x5a\x00Hello World\x3a\xf2",
             ("::1", zep_params['local_port']))
    child.expect(r"RSSI: \d+, LQI: \d+, Data:")
    child.expect_exact(r"00000000  41  DC  02  23  00  38  30  00  0A  50  45  5A  00  5B  45  00")
    child.expect_exact(r"00000010  0A  50  45  5A  00  48  65  6C  6C  6F  20  57  6F  72  6C  64")


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner'))
    import testrunner

    os.environ['TERMFLAGS'] = "-z [%s]:%d,[%s]:%d" % (
            zep_params['local_addr'], zep_params['local_port'],
            zep_params['remote_addr'], zep_params['remote_port'])
    s = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM)
    s.bind(("::", zep_params['remote_port']))
    res = testrunner.run(testfunc, timeout=1, echo=True, traceback=True)
    s.close()
    if (res == 0):
        print("Run tests successful")
    else:
        print("Run tests failed")
    sys.exit(res)
Example #10
0
def testfunc(child):
    global sniffer
    tap = get_bridge(os.environ["TAP"])

    child.expect(r"OK \((\d+) tests\)")     # wait for and check result of unittests
    print("." * int(child.match.group(1)), end="", flush=True)
    lladdr_src = get_host_lladdr(tap)
    child.sendline("ifconfig")
    child.expect("HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)")
    hwaddr_dst = child.match.group("hwaddr").lower()
    child.expect("(?P<lladdr>fe80::[A-Fa-f:0-9]+)")
    lladdr_dst = child.match.group("lladdr").lower()
    sniffer = Sniffer(tap)
    sniffer.start()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_wrong_type)
    run(test_seg_left_gt_len_addresses)
    run(test_multicast_dst)
    run(test_multicast_addr)
    run(test_multiple_addrs_of_mine_uncomp)
    run(test_forward_uncomp)
    run(test_forward_uncomp_not_first_ext_hdr)
    # compressed tests hard to implement with scapy and also covered in
    # unittests
    run(test_seq_left_0)
    run(test_time_exc)
    print("SUCCESS")
    sniffer.stop()
Example #11
0
        print client_address
        print '-'*40

if __name__ == "__main__":
    do_valgrind = False
    path_search = False
    options, args = getopt.getopt(sys.argv[1:], "V", ["valgrind"])
    for option, value in options:
        if option == "-V" or option == "--valgrind":
            do_valgrind = True

    # Instantiate a Server(TestHTTPRequestHandler) on the first free port
    # in the specified port range. Doing this inline is better than in a
    # daemon thread: if it blows up here, we'll get a traceback. If it blew up
    # in some other thread, the traceback would get eaten and we'd run the
    # subject test program anyway.
    httpd, port = freeport(xrange(8000, 8020),
                           lambda port: Server(('127.0.0.1', port), TestHTTPRequestHandler))

    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["LL_TEST_PORT"] = str(port)
    debug("$LL_TEST_PORT = %s", port)
    if do_valgrind:
        args = ["valgrind", "--log-file=./valgrind.log"] + args
        path_search = True
    sys.exit(run(server=Thread(name="httpd", target=httpd.serve_forever), use_path=path_search, *args))

Example #12
0
class InvalidTimeout(Exception):
    pass


def testfunc(child):
    try:
        child.expect_exact("Please hit any key and then ENTER to continue")
        child.sendline("a")
        start_test = time.time()
        child.expect_exact("5 x usleep(i++ * 500000)")
        for i in range(5):
            child.expect_exact("wake up")
        child.expect_exact("5 x sleep(i++)")
        for i in range(5):
            child.expect_exact("wake up")
        child.expect_exact("DONE")
        testtime = (time.time() - start_test) * US_PER_SEC
        exp = sum(i * 500000 for i in range(5)) + \
              sum(i * US_PER_SEC for i in range(5))
        lower_bound = exp - (exp * EXTERNAL_JITTER)
        upper_bound = exp + (exp * EXTERNAL_JITTER)
        if not (lower_bound < testtime < upper_bound):
            raise InvalidTimeout("Host timer measured %d us (client measured %d us)" % \
                                 (testtime, exp))
    except InvalidTimeout as e:
        print(e)
        sys.exit(1)

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, echo=True))
Example #13
0
def testfunc(child):
    global server
    tap = get_bridge(os.environ["TAP"])
    lladdr = get_host_lladdr(tap)

    time.sleep(3)
    try:
        server = Server(family=socket.AF_INET6, type=socket.SOCK_DGRAM,
                        bind_addr=lladdr + "%" + tap, bind_port=SERVER_PORT)
        server.start()
        dns_server(child, lladdr, SERVER_PORT)

        def run(func):
            if child.logfile == sys.stdout:
                print(func.__name__)
                func(child)
            else:
                try:
                    func(child)
                    print(".", end="", flush=True)
                except Exception as e:
                    print("FAILED")
                    raise e

        run(test_success)
        run(test_timeout)
        run(test_too_short_response)
        run(test_qdcount_too_large1)
        run(test_qdcount_too_large2)
        run(test_ancount_too_large1)
        run(test_ancount_too_large2)
        run(test_bad_compressed_message_query)
        run(test_bad_compressed_message_answer)
        run(test_malformed_hostname_query)
        run(test_malformed_hostname_answer)
        run(test_addrlen_too_large)
        run(test_addrlen_wrong_ip6)
        run(test_addrlen_wrong_ip4)
        print("SUCCESS")
    finally:
        if server is not None:
            server.stop()
Example #14
0
from optparse import OptionParser


def makeoptions():
    parser = OptionParser()
    parser.add_option(
        "-v",
        "--verbosity",
        type=int,
        action="store",
        dest="verbosity",
        default=1,
        help="Tests verbosity level, one of 0, 1, 2 or 3",
    )
    return parser


if __name__ == "__main__":
    import djpcms
    import sys

    options, tags = makeoptions().parse_args()
    verbosity = options.verbosity

    p = os.path
    path = p.join(p.split(p.abspath(__file__))[0], "tests")
    sys.path.insert(0, path)
    from testrunner import run

    run(tags, verbosity=verbosity)
Example #15
0
def testfunc(child):
    tap = get_bridge(os.environ["TAP"])

    child.expect(
        r"OK \((\d+) tests\)")  # wait for and check result of unittests
    print("." * int(child.match.group(1)), end="", flush=True)

    lladdr_src = get_host_lladdr(tap)

    def run_sock_test(func, s):
        if child.logfile == sys.stdout:
            func(child, s, tap, lladdr_src)
        else:
            try:
                func(child, s, tap, lladdr_src)
                print(".", end="", flush=True)
            except PermissionError:
                print("\n\x1b[1;33mSkipping {} because of missing "
                      "privileges\x1b[0m".format(func.__name__))
            except Exception as e:
                print("FAILED")
                raise e

    child.expect(r"Sending UDP test packets to port (\d+)")

    port = int(child.match.group(1))
    with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s:
        res = socket.getaddrinfo("{}%{}".format(lladdr_src, tap), port)
        s.bind(res[0][4])
        s.settimeout(.3)
        run_sock_test(test_ipv6_ext_frag_shell_test_0, s)
        run_sock_test(test_ipv6_ext_frag_shell_test_1, s)
        run_sock_test(test_ipv6_ext_frag_send_success, s)
        run_sock_test(test_ipv6_ext_frag_send_last_fragment_filled, s)
        run_sock_test(test_ipv6_ext_frag_send_last_fragment_only_one_byte, s)
        run_sock_test(test_ipv6_ext_frag_send_full_pktbuf, s)
        run_sock_test(test_ipv6_ext_frag_fwd_success, s)
        run_sock_test(test_ipv6_ext_frag_fwd_too_big, s)

    if os.environ.get("BOARD", "") != "native":
        # ethos currently can't handle the larger, rapidly sent packets by the
        # IPv6 fragmentation of the Linux Kernel
        print("SUCCESS")
        print("Skipping datagram reception tests due to ethos bug.")
        return

    # datagram reception tests
    res = 1
    count = 0
    while res:
        # check `ifconfig` and also get addresses from it until
        # link-local address becomes valid
        time.sleep(1)
        child.sendline("ifconfig")
        child.expect("HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)")
        hwaddr_dst = child.match.group("hwaddr").lower()
        res = child.expect([
            r"(?P<lladdr>fe80::[A-Fa-f:0-9]+)\s+scope:\s+local\s+VAL",
            pexpect.TIMEOUT
        ])
        count += 1
        if res and (count > 5):
            raise pexpect.TIMEOUT("Link-local address did not become valid")
    lladdr_dst = child.match.group("lladdr").lower()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except PermissionError:
                print("\n\x1b[1;33mSkipping {} because of missing "
                      "privileges\x1b[0m".format(func.__name__))
            except Exception as e:
                print("FAILED")
                raise e

    run(test_reass_successful_udp)
    run(test_reass_too_short_header)
    run(test_reass_offset_too_large)
    print("SUCCESS")
    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass


if __name__ == "__main__":
    # function to make a server with specified port
    make_server = lambda port: TestServer(('127.0.0.1', port))

    if not sys.platform.startswith("win"):
        # Instantiate a TestServer on a port chosen by the runtime.
        xmlrpcd = make_server(0)
    else:
        # "Then there's Windows"
        # Instantiate a TestServer on the first free port in the specified
        # port range.
        xmlrpcd, port = freeport(range(8000, 8020), make_server)

    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["PORT"] = str(xmlrpcd.server_port)
    sys.exit(run(server_inst=xmlrpcd, *sys.argv[1:]))
Example #17
0
# Copyright (C) 2018 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import sys
from testrunner import run


def testfunc(child):
    child.expect(r"Iface\s+\d+")
    child.expect(r"inet6 addr:\sfe80:[0-9a-f:]+\s+scope: link")
    child.expect(r"Iface\s+\d+")
    child.expect(r"inet6 addr:\s+fe80:[0-9a-f:]+\s+scope: link")
    child.expect(r"inet6 addr:\s+(?P<global_addr>[0-9a-f:]+)\s+scope: global")
    global_addr = child.match.group("global_addr")
    child.expect(r"(?P<global_pfx>[0-9a-f:]+)/64\s+dev #\d\s+"
                 r"expires \d+ sec\s+"
                 r"deprecates \d+ sec")
    global_pfx = child.match.group("global_pfx")
    if global_pfx.endswith("::"):
        # remove one trailing : in case there are no 0s between prefix and
        # suffix
        global_pfx = global_pfx[0:-1]
    assert global_addr.startswith(global_pfx)


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=6))
Example #18
0
File: runner.py Project: tfar/sccd
#!/usr/bin/env python3

# Copyright (C) 2016 Kaspar Schleiser <*****@*****.**>
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import os
import sys

sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner'))
import testrunner

def testfunc(child):
    child.expect(u"done")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, 1200))
Example #19
0
    while (m):
        n = 3
        while (n):
            if n == 3:
                exp_diff = exp_diff1
            if n == 2:
                exp_diff = exp_diff5
            elif n == 1:
                exp_diff = exp_diff10
            start = datetime.now()
            child.expect(u"Slept for \\d+ sec...", timeout=11)
            stop = datetime.now()
            diff = (stop - start)
            diff = (diff.seconds * 1000000) + diff.microseconds
            # fail within 5% of expected
            if diff > (exp_diff + (exp_diff1 * 0.05)) or \
               diff < (exp_diff - (exp_diff1 * 0.05)):
                raise InvalidTimeout("Invalid timeout %d (expected %d)" %
                                     (diff, exp_diff))
            else:
                print("Timed out correctly: %d (expected %d)" %
                      (diff, exp_diff))
            n = n - 1
        m = m - 1

    child.expect(u"Test end.", timeout=15)


if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc))
        def log_error(self, format, *args):
            # Suppress error output as well
            pass


class Server(HTTPServer):
    # This pernicious flag is on by default in HTTPServer. But proper
    # operation of freeport() absolutely depends on it being off.
    allow_reuse_address = False


if __name__ == "__main__":
    # Instantiate a Server(TestHTTPRequestHandler) on the first free port
    # in the specified port range. Doing this inline is better than in a
    # daemon thread: if it blows up here, we'll get a traceback. If it blew up
    # in some other thread, the traceback would get eaten and we'd run the
    # subject test program anyway.
    httpd, port = freeport(
        xrange(8000, 8020), lambda port: Server(
            ('127.0.0.1', port), TestHTTPRequestHandler))
    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["PORT"] = str(port)
    debug("$PORT = %s", port)
    sys.exit(
        run(server=Thread(name="httpd", target=httpd.serve_forever),
            *sys.argv[1:]))
Example #21
0
            raise Exception('method "%s" is not supported' % method)
        else:
            # LLXMLRPCListener constructs XMLRPC parameters that arrive as a
            # 1-tuple containing a dict.
            return func(**(params[0]))

    def hello(self, who):
        # LLXMLRPCListener expects a dict return.
        return {"hi_there": "Hello, %s!" % who}

    def getdict(self):
        return dict(nested_dict=dict(a=17, b=5))

    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass

class ServerRunner(Thread):
    def run(self):
        server = TestServer(('127.0.0.1', 8000))
        debug("Starting XMLRPC server...\n")
        server.serve_forever()

if __name__ == "__main__":
    sys.exit(run(server=ServerRunner(name="xmlrpc"), *sys.argv[1:]))
Example #22
0
    child.expect_exact('(double, 2.000000)')
    child.expect_exact('(byte string, "abc")')
    child.expect_exact('(unicode string, "def")')
    child.expect_exact('(array, length: 2)')
    child.expect_exact('  (uint64_t, 0)')
    child.expect_exact('  (uint64_t, 1)')
    child.expect_exact('(array, length: [indefinite])')
    child.expect_exact('  (uint64_t, 10)')
    child.expect_exact('  (uint64_t, 11)')
    child.expect_exact('(map, length: 2)')
    child.expect_exact(' (uint64_t, 1)')
    child.expect_exact('  (byte string, "1")')
    child.expect_exact(' (uint64_t, 2)')
    child.expect_exact('  (byte string, "2")')
    child.expect_exact('(map, length: [indefinite])')
    child.expect_exact(' (uint64_t, 10)')
    child.expect_exact('  (byte string, "10")')
    child.expect_exact(' (uint64_t, 11)')
    child.expect_exact('  (byte string, "11")')
    child.expect(r'\(tag: 0, date/time string: "[\w :]+"\)')
    child.expect(r'\(tag: 1, date/time epoch: \d+\)')
    child.expect_exact('(unsupported, 0xC2')
    child.expect_exact(')')
    child.expect_exact('(byte string, "1")')

    print("All tests successful")


if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, echo=False))
Example #23
0
        child.expect_exact("Calling test_tcp_connect6__EINVAL_netif()")
        child.expect_exact("Calling test_tcp_connect6__success_without_port()")
        child.expect_exact("Calling test_tcp_connect6__success_local_port()")
        if _reuse_tests(code):
            child.expect_exact("Calling test_tcp_listen6__EADDRINUSE()")
        child.expect_exact("Calling test_tcp_listen6__EAFNOSUPPORT()")
        child.expect_exact("Calling test_tcp_listen6__EINVAL()")
        child.expect_exact("Calling test_tcp_listen6__success_any_netif()")
        child.expect_exact("Calling test_tcp_listen6__success_spec_netif()")
        child.expect_exact("Calling test_tcp_accept6__EAGAIN()")
        child.expect_exact("Calling test_tcp_accept6__EINVAL()")
        child.expect_exact("Calling test_tcp_accept6__ETIMEDOUT()")
        child.expect_exact(" * Calling sock_tcp_accept()")
        child.expect(r" \* \(timed out with timeout \d+\)")
        child.expect_exact("Calling test_tcp_accept6__success()")
        child.expect_exact("Calling test_tcp_read6__EAGAIN()")
        child.expect_exact("Calling test_tcp_read6__ECONNRESET()")
        child.expect_exact("Calling test_tcp_read6__ENOTCONN()")
        child.expect_exact("Calling test_tcp_read6__ETIMEDOUT()")
        child.expect_exact(" * Calling sock_tcp_read()")
        child.expect(r" \* \(timed out with timeout \d+\)")
        child.expect_exact("Calling test_tcp_read6__success()")
        child.expect_exact("Calling test_tcp_read6__success_with_timeout()")
        child.expect_exact("Calling test_tcp_read6__success_non_blocking()")
        child.expect_exact("Calling test_tcp_write6__ENOTCONN()")
        child.expect_exact("Calling test_tcp_write6__success()")
    child.expect_exact(u"ALL TESTS SUCCESSFUL")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, timeout=60))
Example #24
0
    assert DHCP6OptClientId in pkt and DUID_LL in pkt[DHCP6OptClientId].duid
    assert pkt[DHCP6OptClientId].duid[DUID_LL].lladdr in upstream_hwaddrs
    # and it is trying to talk to this server
    assert DHCP6OptServerId in pkt and DUID_LL in pkt[DHCP6OptServerId].duid
    assert pkt[DHCP6OptServerId].duid[DUID_LL].lladdr == srv_duid
    # and is still asking for a prefix delegation
    assert DHCP6OptIA_PD in pkt

    assert DHCP6OptMUD in pkt
    mud_option = pkt[DHCP6OptMUD]
    assert mud_option.optcode == 112
    assert mud_option.optlen == len(MUD_TEST_URL)
    assert mud_option.data == MUD_TEST_URL

    # reply to request with reply and a prefix provided
    trid = pkt[DHCP6_Request].trid
    sendp(build_reply_headers(pkt) / DHCP6_Reply(trid=trid) /
          ia_pd / cli_id / srv_id, iface=iface, verbose=False)
    time.sleep(1)

    # check if global address was configured
    child.sendline("ifconfig {}".format(get_downstream_netif(child)))
    # remove one trailing ':' from prefix just to be safe ;-)
    child.expect(r"inet6 addr:\s+{}[0-9a-fA-F:]+\s"
                 .format(prefix[:-1]))
    print("SUCCESS")


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=TIMEOUT, echo=True))
                "reason",
                self.responses.get(
                    status,
                    (
                        "fail requested",
                        "Your request specified failure status %s " "without providing a reason" % status,
                    ),
                )[1],
            )
            self.send_error(status, reason)

    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass


class TestHTTPServer(Thread):
    def run(self):
        httpd = HTTPServer(("127.0.0.1", 8000), TestHTTPRequestHandler)
        debug("Starting HTTP server...\n")
        httpd.serve_forever()


if __name__ == "__main__":
    sys.exit(run(server=TestHTTPServer(name="httpd"), *sys.argv[1:]))
Example #26
0
    child.expect_exact("Waiting for an incoming message (use `make test`)")
    s.sendto(
        b"\x45\x58\x02\x01\x1a\x44\xe0\x01\xff\xdb\xde\xa6\x1a\x00\x8b" +
        b"\xfd\xae\x60\xd3\x21\xf1\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
        b"\x00\x22\x41\xdc\x02\x23\x00\x38\x30\x00\x0a\x50\x45\x5a\x00" +
        b"\x5b\x45\x00\x0a\x50\x45\x5a\x00Hello World\x3a\xf2",
        ("127.0.0.1", zep_params['local_port']))
    child.expect(r"RSSI: \d+, LQI: \d+, Data:")
    child.expect_exact(
        r"00000000  41  DC  02  23  00  38  30  00  0A  50  45  5A  00  5B  45  00"
    )
    child.expect_exact(
        r"00000010  0A  50  45  5A  00  48  65  6C  6C  6F  20  57  6F  72  6C  64"
    )


if __name__ == "__main__":
    os.environ[
        'TERMFLAGS'] = "--eui64=00:5a:45:50:0a:00:30:38 -z [%s]:%d,[%s]:%d" % (
            zep_params['local_addr'], zep_params['local_port'],
            zep_params['remote_addr'], zep_params['remote_port'])
    s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    s.bind(("127.0.0.1", zep_params['remote_port']))
    res = run(testfunc, timeout=1, echo=True, traceback=True)
    s.close()
    if (res == 0):
        print("Run tests successful")
    else:
        print("Run tests failed")
    sys.exit(res)
Example #27
0
#!/usr/bin/env python3

# Copyright (C) 2016 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import sys
from testrunner import run


def testfunc(child):
    child.expect(r"TRACE_SIZE: (\d+)")
    trace_size = int(child.match.group(1))
    for i in range(trace_size):
        child.expect("0x[0-9a-f]{7,8}")

    print("All tests successful")


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=1, echo=True, traceback=True))
            # LLXMLRPCListener constructs XMLRPC parameters that arrive as a
            # 1-tuple containing a dict.
            return func(**(params[0]))

    def hello(self, who):
        # LLXMLRPCListener expects a dict return.
        return {"hi_there": "Hello, %s!" % who}

    def getdict(self):
        return dict(nested_dict=dict(a=17, b=5))

    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass


class ServerRunner(Thread):
    def run(self):
        server = TestServer(('127.0.0.1', 8000))
        debug("Starting XMLRPC server...\n")
        server.serve_forever()


if __name__ == "__main__":
    sys.exit(run(server=ServerRunner(name="xmlrpc"), *sys.argv[1:]))
        child, half_data_len) == data[:half_data_len]

    # Read half the test data without timeout. Verify Buffer contents
    child.sendline('gnrc_tcp_recv 0 ' + str(half_data_len))
    child.expect_exact('gnrc_tcp_recv: received ' + str(half_data_len))
    assert read_data_from_internal_buffer(
        child, half_data_len) == data[half_data_len:]

    # Buffer should have been read entirly and the connection was closed, there can be no new data.
    # Reading with a timeout must return 0 not -ETIMEOUT
    child.sendline('gnrc_tcp_recv 1000000 ' + str(half_data_len))
    child.expect_exact('gnrc_tcp_recv: returns 0')

    # Reading without a timeout must return 0 not -EAGAIN.
    child.sendline('gnrc_tcp_recv 0 ' + str(half_data_len))
    child.expect_exact('gnrc_tcp_recv: returns 0')

    # Close connection
    child.sendline('gnrc_tcp_close')
    server_handle.join()

    verify_pktbuf_empty(child)

    # Verify received Data
    print(os.path.basename(sys.argv[0]) + ': success')


if __name__ == '__main__':
    sudo_guard()
    sys.exit(run(testfunc, timeout=5, echo=False, traceback=True))
Example #30
0
class InvalidTimeout(Exception):
    pass


def testfunc(child):
    try:
        child.expect_exact("Please hit any key and then ENTER to continue")
        child.sendline("a")
        start_test = time.time()
        child.expect_exact("5 x usleep(i++ * 500000)")
        for i in range(5):
            child.expect_exact("wake up")
        child.expect_exact("5 x sleep(i++)")
        for i in range(5):
            child.expect_exact("wake up")
        child.expect_exact("DONE")
        testtime = (time.time() - start_test) * US_PER_SEC
        exp = sum(i * 500000 for i in range(5)) + \
            sum(i * US_PER_SEC for i in range(5))
        lower_bound = exp - (exp * EXTERNAL_JITTER)
        upper_bound = exp + (exp * EXTERNAL_JITTER)
        if not (lower_bound < testtime < upper_bound):
            raise InvalidTimeout("Host timer measured %d us (client measured %d us)" % \
                                 (testtime, exp))
    except InvalidTimeout as e:
        print(e)
        sys.exit(1)

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, echo=True))
Example #31
0
# directory for more details.

# Tell the lua interpreter running in riot to load some modules and print
# the value of a variable inside that module.

import os
import sys

MODULE_QUERIES = [
    ("m1", "a", "Quando uma lua"),
    ("m2", "a", "chega de repente"),
    ("c1", "X", "E se deixa no céu,"),
    ("c2", "X", "como esquecida"),
]


def test(child):
    # check startup message
    child.expect_exact('I am a module, hi!')

    # loop other defined commands and expected output
    for mod, attr, val in MODULE_QUERIES:
        child.sendline('print((require"{}").{})'.format(mod, attr))
        child.expect_exact(val)


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTTOOLS'], 'testrunner'))
    from testrunner import run
    sys.exit(run(test))
Example #32
0
def testfunc(child):
    tap = get_bridge(os.environ["TAP"])

    lladdr_src = get_host_lladdr(tap)
    child.sendline("ifconfig")
    child.expect(r"HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)\s")
    hwaddr_dst = child.match.group("hwaddr").lower()
    child.expect(r"(?P<lladdr>fe80::[A-Fa-f:0-9]+)\s")
    lladdr_dst = child.match.group("lladdr").lower()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_empty_hop_by_hop_opt_wo_register)
    run(test_empty_hop_by_hop_opt_w_register)
    run(test_empty_duplicate_hop_by_hop_opt)
    run(test_empty_non_first_hop_by_hop_opt)
    run(test_empty_duplicate_non_first_hop_by_hop_opt)
    run(test_hop_by_hop_opt_only_one_pad1)
    run(test_hop_by_hop_opt_7_pad1)
    run(test_hop_by_hop_opt_broken_padn)
    run(test_hop_by_hop_opt_skip_unknown)
    run(test_hop_by_hop_opt_discard_unknown_1)
    run(test_hop_by_hop_opt_discard_unknown_2)
    run(test_hop_by_hop_opt_discard_unknown_3)
    run(test_hop_by_hop_opt_discard_unknown_3_mcast)
    run(test_hop_by_hop_opt_discard_unknown_4)
    run(test_hop_by_hop_opt_discard_unknown_5)
    run(test_hop_by_hop_opt_discard_unknown_5_mcast)
    run(test_empty_dst_opt_wo_register)
    run(test_empty_dst_opt_w_register)
    run(test_empty_dst_opt_large_hdr_len)
    run(test_dst_opt_only_one_pad1)
    run(test_dst_opt_7_pad1)
    run(test_dst_opt_broken_padn)
    print("SUCCESS")
Example #33
0
#!/usr/bin/env python3

# Copyright (C) 2016 Kaspar Schleiser <*****@*****.**>
# Copyright (C) 2016 Takuo Yonezawa <*****@*****.**>
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import os
import sys

sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner'))
import testrunner


def testfunc(child):
    child.expect(r"OK \(\d+ tests\)")


if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, timeout=1))
Example #34
0
import os
import sys

ACCEPTED_ERROR = 20


def testfunc(child):
    child.expect(r"Testing generic evtimer \(start time = (\d+) ms\)")
    timer_offset = int(child.match.group(1))
    child.expect(
        r"Are the reception times of all (\d+) msgs close to the supposed values?"
    )
    numof = int(child.match.group(1))

    for i in range(numof):
        child.expect(
            r'At \s*(\d+) ms received msg %i: "supposed to be (\d+)"' % i)
        # check if output is correct
        exp = int(child.match.group(2)) + timer_offset
        assert (int(child.match.group(1)) in range(exp - ACCEPTED_ERROR,
                                                   exp + ACCEPTED_ERROR + 1))
        print(".", end="", flush=True)
    print("")
    print("All tests successful")


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTTOOLS'], 'testrunner'))
    from testrunner import run
    sys.exit(run(testfunc, echo=False))
Example #35
0
#!/usr/bin/env python3

# Copyright (C) 2016 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

from __future__ import print_function
import os
import sys

sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner'))
import testrunner

how_many = 100


def testfunc(child):
    for i in range(how_many):
        for j in range(8):
            child.expect(r'received msg "%i"' % (j + 1))
        print(".", end="", flush=True)
    print("")
    print("Stopped after %i iterations, but should run forever." % how_many)
    print("=> All tests successful")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, echo=False))
Example #36
0
    data, addr = s.recvfrom(RCVBUF_LEN)
    assert(len(data) == (ZEP_DATA_HEADER_SIZE + FCS_LEN))
    child.expect_exact("Send 'Hello\\0World\\0'")
    data, addr = s.recvfrom(RCVBUF_LEN)
    assert(len(data) == (ZEP_DATA_HEADER_SIZE + len("Hello\0World\0") + FCS_LEN))
    assert(b"Hello\0World\0" == data[ZEP_DATA_HEADER_SIZE:-2])
    child.expect_exact("Waiting for an incoming message (use `make test`)")
    s.sendto(b"\x45\x58\x02\x01\x1a\x44\xe0\x01\xff\xdb\xde\xa6\x1a\x00\x8b" +
             b"\xfd\xae\x60\xd3\x21\xf1\x00\x00\x00\x00\x00\x00\x00\x00\x00" +
             b"\x00\x22\x41\xdc\x02\x23\x00\x38\x30\x00\x0a\x50\x45\x5a\x00" +
             b"\x5b\x45\x00\x0a\x50\x45\x5a\x00Hello World\x3a\xf2",
             ("::1", zep_params['local_port']))
    child.expect(r"RSSI: \d+, LQI: \d+, Data:")
    child.expect_exact(r"00000000  41  DC  02  23  00  38  30  00  0A  50  45  5A  00  5B  45  00")
    child.expect_exact(r"00000010  0A  50  45  5A  00  48  65  6C  6C  6F  20  57  6F  72  6C  64")


if __name__ == "__main__":
    os.environ['TERMFLAGS'] = "-z [%s]:%d,[%s]:%d" % (
            zep_params['local_addr'], zep_params['local_port'],
            zep_params['remote_addr'], zep_params['remote_port'])
    s = socket.socket(family=socket.AF_INET6, type=socket.SOCK_DGRAM)
    s.bind(("::", zep_params['remote_port']))
    res = run(testfunc, timeout=1, echo=True, traceback=True)
    s.close()
    if (res == 0):
        print("Run tests successful")
    else:
        print("Run tests failed")
    sys.exit(res)
Example #37
0
def testfunc(child):
    global sniffer
    tap = get_bridge(os.environ["TAP"])
    child.sendline("unittests")
    child.expect(
        r"OK \((\d+) tests\)")  # wait for and check result of unittests
    print("." * int(child.match.group(1)), end="", flush=True)
    lladdr_src = get_host_lladdr(tap)
    child.sendline("ifconfig")
    child.expect(r"HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)\s")
    hwaddr_dst = child.match.group("hwaddr").lower()
    child.expect(r"(?P<lladdr>fe80::[A-Fa-f:0-9]+)\s")
    lladdr_dst = child.match.group("lladdr").lower()
    sniffer = Sniffer(tap)
    sniffer.start()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_wrong_type)
    run(test_seg_left_gt_len_addresses)
    run(test_multicast_dst)
    run(test_multicast_addr)
    run(test_multiple_addrs_of_mine_uncomp)
    run(test_forward_uncomp)
    run(test_forward_uncomp_not_first_ext_hdr)
    # compressed tests hard to implement with scapy and also covered in
    # unittests
    run(test_seq_left_0)
    run(test_time_exc)
    print("SUCCESS")
    sniffer.stop()
Example #38
0
        if child.logfile == sys.stdout:
            func(child, client, current_app_ver)
        else:
            try:
                func(child, client, current_app_ver)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(_test_invalid_signature)
    run(_test_invalid_version)
    run(_test_successful_update)

    print("TEST PASSED")


if __name__ == "__main__":
    try:
        res = 1
        aiocoap_process = start_aiocoap_fileserver()
        # TODO: wait for coap port to be available
        res = run(testfunc, echo=True)

    except Exception as e:
        print(e)
    finally:
        cleanup(aiocoap_process)

    sys.exit(res)
Example #39
0
#!/usr/bin/env python3

# Copyright (C) 2016 Kaspar Schleiser <*****@*****.**>
#               2017 Sebastian Meiling <*****@*****.**>
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

import sys
from testrunner import run


def testfunc(child):
    child.expect_exact("[SUCCESS]", timeout=60)


if __name__ == "__main__":
    sys.exit(run(testfunc))
Example #40
0
         "data_len_step": 50},
        {"qos_level": 1, "mode": "sub",
         "topic_name": "/" + ("x" * (TOPIC_MAX_LEN - 1)),
         "data_len_start": 8, "data_len_end": 9},
        {"qos_level": 1, "mode": "sub_w_reg", "topic_name": "/test",
         "data_len_start": 8, "data_len_end": 9},
        {"qos_level": 0, "mode": "pub", "topic_name": "/test",
         "data_len_start": 1, "data_len_end": DATA_MAX_LEN,
         "data_len_step": 50},
        {"qos_level": 1, "mode": "pub", "topic_name": "/test",
         "data_len_start": 1, "data_len_end": DATA_MAX_LEN,
         "data_len_step": 50}
    ]:
        print("Run test case")
        pprint.pprint(test_params, compact=False)
        server = MQTTSNServer(child, pub_interval=.001,
                              family=socket.AF_INET6,
                              bind_addr=lladdr + "%" + tap,
                              bind_port=SERVER_PORT, **test_params)
        try:
            server.run()
        finally:
            server.stop()
            server.socket_kargs["sock"].close()
            time.sleep(1)
    print("SUCCESS")


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=TIMEOUT, echo=False))
Example #41
0
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), OD_WIDTH_DEFAULT)")
    child.expect_exact("00000000  FF  2C  61  FF  2E  62  63  64  65  66  67  68  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 4)")
    child.expect_exact("00000000  FF  2C  61  FF")
    child.expect_exact("00000004  2E  62  63  64")
    child.expect_exact("00000008  65  66  67  68")
    child.expect_exact("0000000C  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70")
    child.expect_exact("00000014  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 3)")
    child.expect_exact("00000000  FF  2C  61")
    child.expect_exact("00000003  FF  2E  62")
    child.expect_exact("00000006  63  64  65")
    child.expect_exact("00000009  66  67  68")
    child.expect_exact("0000000C  69  6A  6B")
    child.expect_exact("0000000F  6C  6D  6E")
    child.expect_exact("00000012  6F  70  00")
    child.expect_exact("od_hex_dump(long_str, sizeof(long_str), 8)")
    child.expect_exact("00000000  FF  2C  61  FF  2E  62  63  64")
    child.expect_exact("00000008  65  66  67  68  69  6A  6B  6C")
    child.expect_exact("00000010  6D  6E  6F  70  00")

    print("All tests successful")


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTTOOLS'], 'testrunner'))
    from testrunner import run
    sys.exit(run(testfunc, timeout=1, echo=False))
    path_search = False
    options, args = getopt.getopt(sys.argv[1:], "V", ["valgrind"])
    for option, value in options:
        if option == "-V" or option == "--valgrind":
            do_valgrind = True

    # function to make a server with specified port
    make_server = lambda port: Server(
        ('127.0.0.1', port), TestHTTPRequestHandler)

    if not sys.platform.startswith("win"):
        # Instantiate a Server(TestHTTPRequestHandler) on a port chosen by the
        # runtime.
        httpd = make_server(0)
    else:
        # "Then there's Windows"
        # Instantiate a Server(TestHTTPRequestHandler) on the first free port
        # in the specified port range.
        httpd, port = freeport(xrange(8000, 8020), make_server)

    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["LL_TEST_PORT"] = str(httpd.server_port)
    debug("$LL_TEST_PORT = %s", httpd.server_port)
    if do_valgrind:
        args = ["valgrind", "--log-file=./valgrind.log"] + args
        path_search = True
    sys.exit(run(server_inst=httpd, use_path=path_search, *args))
Example #43
0
    def hello(self, who):
        # LLXMLRPCListener expects a dict return.
        return {"hi_there": "Hello, %s!" % who}

    def getdict(self):
        return dict(nested_dict=dict(a=17, b=5))

    def log_request(self, code, size=None):
        # For present purposes, we don't want the request splattered onto
        # stderr, as it would upset devs watching the test run
        pass

    def log_error(self, format, *args):
        # Suppress error output as well
        pass

if __name__ == "__main__":
    # Instantiate a TestServer on the first free port in the specified port
    # range. Doing this inline is better than in a daemon thread: if it blows
    # up here, we'll get a traceback. If it blew up in some other thread, the
    # traceback would get eaten and we'd run the subject test program anyway.
    xmlrpcd, port = freeport(xrange(8000, 8020),
                             lambda port: TestServer(('127.0.0.1', port)))
    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["PORT"] = str(port)
    sys.exit(run(server=Thread(name="xmlrpc", target=xmlrpcd.serve_forever), *sys.argv[1:]))
Example #44
0
import sys

from testrunner import run


def testfunc(child):
    # VLIM
    child.sendline("bq2429x_set_vlim 15")
    child.expect(r"VLIM set to 5080 mV")
    child.sendline("bq2429x_get_vlim")
    child.expect(r"VLIM: 5080 mV")
    # ILIM
    child.sendline("bq2429x_set_ilim 2")
    child.expect(r"ILIM set to 500 mA")
    child.sendline("bq2429x_get_ilim")
    child.expect(r"ILIM: 500 mA")
    # ICHG
    child.sendline("bq2429x_set_ichg 0")
    child.expect(r"ICHG set to 512 mA")
    child.sendline("bq2429x_get_ichg")
    child.expect(r"ICHG: 512 mA")
    # VREG
    child.sendline("bq2429x_set_vreg 6")
    child.expect(r"VREG set to 4208 mV")
    child.sendline("bq2429x_get_vreg")
    child.expect(r"VREG: 4208 mV")


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=5, echo=True))
        def log_request(self, code, size=None):
            # For present purposes, we don't want the request splattered onto
            # stderr, as it would upset devs watching the test run
            pass

        def log_error(self, format, *args):
            # Suppress error output as well
            pass

class Server(HTTPServer):
    # This pernicious flag is on by default in HTTPServer. But proper
    # operation of freeport() absolutely depends on it being off.
    allow_reuse_address = False

if __name__ == "__main__":
    # Instantiate a Server(TestHTTPRequestHandler) on the first free port
    # in the specified port range. Doing this inline is better than in a
    # daemon thread: if it blows up here, we'll get a traceback. If it blew up
    # in some other thread, the traceback would get eaten and we'd run the
    # subject test program anyway.
    httpd, port = freeport(xrange(8000, 8020),
                           lambda port: Server(('127.0.0.1', port), TestHTTPRequestHandler))
    # Pass the selected port number to the subject test program via the
    # environment. We don't want to impose requirements on the test program's
    # command-line parsing -- and anyway, for C++ integration tests, that's
    # performed in TUT code rather than our own.
    os.environ["PORT"] = str(port)
    debug("$PORT = %s", port)
    sys.exit(run(server=Thread(name="httpd", target=httpd.serve_forever), *sys.argv[1:]))
Example #46
0
    tcp_hdr = TCP(dport=dst_port, flags="S", sport=2342, seq=1, dataofs=6)
    sendp(Ether(dst=dst_l2) / IPv6(src=src_ll, dst=dst_ll) / tcp_hdr /
          b"\x50\x00\x00\x00",
          iface=src_if,
          verbose=0)

    # check if server actually still works
    with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as sock:
        sock.settimeout(child.timeout)
        addr_info = socket.getaddrinfo(dst_ll + '%' + src_if,
                                       dst_port,
                                       type=socket.SOCK_STREAM)
        sock.connect(addr_info[0][-1])
        child.expect_exact('gnrc_tcp_open_passive: returns 0')
    verify_pktbuf_empty(child)


if __name__ == "__main__":
    sudo_guard(uses_scapy=True)
    script = sys.modules[__name__]
    tests = [
        getattr(script, t) for t in script.__dict__
        if type(getattr(script, t)).__name__ == "function"
        and t.startswith("test_")
    ]
    for test in tests:
        res = run(test, timeout=10, echo=False)
        if res != 0:
            sys.exit(res)
    print(os.path.basename(sys.argv[0]) + ": success\n")
Example #47
0
    child.expect(r"pktdump dumping IEEE 802\.15\.4 packet with payload 12 34 45 56")
    child.expect("PKTDUMP: data received:")
    child.expect(r"~~ SNIP  0 - size:   4 byte, type: NETTYPE_UNDEF \(0\)")
    child.expect("00000000  12  34  45  56")
    child.expect(r"~~ SNIP  1 - size:  24 byte, type: NETTYPE_NETIF \(-1\)")
    child.expect(r"if_pid: \d+  rssi: \d+  lqi: \d+")
    child.expect("flags: 0x0")
    child.expect("src_l2addr: 3e:e6:b5:0f:19:22:fd:0b")
    child.expect("dst_l2addr: 3e:e6:b5:0f:19:22:fd:0a")
    child.expect("~~ PKT    -  2 snips, total size:  28 byte")
    # test_netapi_recv__ipv6_ethernet_payload
    child.expect("pktdump dumping IPv6 over Ethernet packet with payload 01")
    child.expect("PKTDUMP: data received:")
    # payload not dumped because not parsed yet, but header looks okay, so let's
    # assume the payload is as well
    child.expect(r"~~ SNIP  0 - size:  41 byte, type: NETTYPE_IPV6 \(2\)")
    child.expect(r"traffic class: 0x00 \(ECN: 0x0, DSCP: 0x00\)")
    child.expect("flow label: 0x00000")
    child.expect("length: 1  next header: 59  hop limit: 64")
    child.expect("source address: fe80::3fe6:b5ff:fe22:fd0a")
    child.expect("destination address: fe80::3fe6:b5ff:fe22:fd0b")
    child.expect(r"~~ SNIP  1 - size:  20 byte, type: NETTYPE_NETIF \(-1\)")
    child.expect(r"if_pid: \d+  rssi: \d+  lqi: \d+")
    child.expect("flags: 0x0")
    child.expect("src_l2addr: 3e:e6:b5:22:fd:0b")
    child.expect("dst_l2addr: 3e:e6:b5:22:fd:0a")
    child.expect("~~ PKT    -  2 snips, total size:  61 byte")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, timeout=1, traceback=True))
Example #48
0
    child.expect_exact(r'000000020 6e6d 706f 0000')
    child.expect_exact(
        r'od(long_str, sizeof(long_str), OD_WIDTH_DEFAULT, OD_FLAGS_BYTES_INT | OD_FLAGS_LENGTH_LONG)'
    )
    child.expect_exact(
        r'000000000    -10408705   1684234798   1751606885   1818978921')
    child.expect_exact(r'000000020   1886350957            0')
    child.expect_exact(
        r'od(long_str, sizeof(long_str), OD_WIDTH_DEFAULT, OD_FLAGS_BYTES_DECIMAL | OD_FLAGS_LENGTH_LONG)'
    )
    child.expect_exact(
        r'000000000    -10408705   1684234798   1751606885   1818978921')
    child.expect_exact(r'000000020   1886350957            0')
    child.expect_exact(
        r'od(long_str, sizeof(long_str), OD_WIDTH_DEFAULT, OD_FLAGS_BYTES_UINT | OD_FLAGS_LENGTH_LONG)'
    )
    child.expect_exact(
        r'000000000   4284558591   1684234798   1751606885   1818978921')
    child.expect_exact(r'000000020   1886350957            0')
    child.expect_exact(
        r'od(long_str, sizeof(long_str), OD_WIDTH_DEFAULT, OD_FLAGS_BYTES_HEX | OD_FLAGS_LENGTH_LONG)'
    )
    child.expect_exact(r'000000000 ff612cff 6463622e 68676665 6c6b6a69')
    child.expect_exact(r'000000020 706f6e6d 00000000')

    print("All tests successful")


if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc, timeout=1, echo=False))
Example #49
0
#!/usr/bin/env python3

import sys
from testrunner import run


# Use a custom global timeout for slow hardware. On microbit (nrf51), the
# test completes in 80s.
TIMEOUT = 100


def testfunc(child):
    child.expect_exact('micro-ecc compiled!')
    child.expect_exact('Testing 16 random private key pairs and signature '
                       'without using HWRNG')
    child.expect_exact('................ done with 0 error(s)')
    child.expect_exact('SUCCESS')


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=TIMEOUT))
Example #50
0
    child.expect("00000000  12  34  45  56")
    child.expect(r"~~ SNIP  1 - size:  \d+ byte, type: NETTYPE_NETIF \(-1\)")
    child.expect(r"if_pid: (\d+)  rssi: -?\d+  lqi: \d+")
    assert 0 < int(child.match.group(1))
    child.expect("flags: 0x0")
    child.expect("src_l2addr: 3E:E6:B5:0F:19:22:FD:0B")
    child.expect("dst_l2addr: 3E:E6:B5:0F:19:22:FD:0A")
    child.expect(r"~~ PKT    -  2 snips, total size:  \d+ byte")
    # test_netapi_recv__ipv6_ethernet_payload
    child.expect("pktdump dumping IPv6 over Ethernet packet with payload 01")
    child.expect("PKTDUMP: data received:")
    # payload not dumped because not parsed yet, but header looks okay, so let's
    # assume the payload is as well
    child.expect(r"~~ SNIP  0 - size:  41 byte, type: NETTYPE_IPV6 \(2\)")
    child.expect(r"traffic class: 0x00 \(ECN: 0x0, DSCP: 0x00\)")
    child.expect("flow label: 0x00000")
    child.expect("length: 1  next header: 59  hop limit: 64")
    child.expect("source address: fe80::3fe6:b5ff:fe22:fd0a")
    child.expect("destination address: fe80::3fe6:b5ff:fe22:fd0b")
    child.expect(r"~~ SNIP  1 - size:  \d+ byte, type: NETTYPE_NETIF \(-1\)")
    child.expect(r"if_pid: (\d+)  rssi: -?\d+  lqi: \d+")
    assert 0 < int(child.match.group(1))
    child.expect("flags: 0x0")
    child.expect("src_l2addr: 3E:E6:B5:22:FD:0B")
    child.expect("dst_l2addr: 3E:E6:B5:22:FD:0A")
    child.expect(r"~~ PKT    -  2 snips, total size:  \d+ byte")


if __name__ == "__main__":
    sys.exit(run(testfunc, timeout=1, traceback=True))
Example #51
0
#!/usr/bin/env python3

# Copyright (C) 2016 Freie Universität Berlin
#
# This file is subject to the terms and conditions of the GNU Lesser
# General Public License v2.1. See the file LICENSE in the top level
# directory for more details.

from __future__ import print_function
import os
import sys

how_many = 100


def testfunc(child):
    for i in range(how_many):
        for j in range(8):
            child.expect(r'received msg "%i"' % (j + 1))
        print(".", end="", flush=True)
    print("")
    print("Stopped after %i iterations, but should run forever." % how_many)
    print("=> All tests successful")


if __name__ == "__main__":
    sys.path.append(os.path.join(os.environ['RIOTBASE'], 'dist/tools/testrunner'))
    from testrunner import run
    sys.exit(run(testfunc, echo=False))
Example #52
0
def testfunc(child):
    global server
    tap = get_bridge(os.environ["TAP"])
    lladdr = get_host_lladdr(tap)

    try:
        server = Server(family=socket.AF_INET6,
                        type=socket.SOCK_DGRAM,
                        bind_addr=lladdr + "%" + tap,
                        bind_port=SERVER_PORT)
        server.start()
        dns_server(child, lladdr, SERVER_PORT)

        def run(func):
            if child.logfile == sys.stdout:
                print(func.__name__)
                func(child)
            else:
                try:
                    func(child)
                    print(".", end="", flush=True)
                except Exception as e:
                    print("FAILED")
                    raise e

        run(test_success)
        run(test_timeout)
        run(test_too_short_response)
        run(test_qdcount_too_large1)
        run(test_qdcount_too_large2)
        run(test_ancount_too_large1)
        run(test_ancount_too_large2)
        run(test_bad_compressed_message_query)
        run(test_bad_compressed_message_answer)
        run(test_malformed_hostname_query)
        run(test_malformed_hostname_answer)
        run(test_addrlen_too_large)
        run(test_addrlen_wrong_ip6)
        run(test_addrlen_wrong_ip4)
        print("SUCCESS")
    finally:
        if server is not None:
            server.stop()
Example #53
0
       diff < (exp_diff - (exp_diff * 0.05)):
        raise InvalidTimeout("Invalid timeout %d (expected %d)" % (diff, exp_diff));
    else:
        print("Timed out correctly: %d (expected %d)" % (diff, exp_diff))
    child.expect_exact(u"Calling test_sock_udp_recv__socketed()")
    child.expect_exact(u"Calling test_sock_udp_recv__socketed_with_remote()")
    child.expect_exact(u"Calling test_sock_udp_recv__unsocketed()")
    child.expect_exact(u"Calling test_sock_udp_recv__unsocketed_with_remote()")
    child.expect_exact(u"Calling test_sock_udp_recv__with_timeout()")
    child.expect_exact(u"Calling test_sock_udp_recv__non_blocking()")
    child.expect_exact(u"Calling test_sock_udp_send__EAFNOSUPPORT()")
    child.expect_exact(u"Calling test_sock_udp_send__EINVAL_addr()")
    child.expect_exact(u"Calling test_sock_udp_send__EINVAL_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__EINVAL_port()")
    child.expect_exact(u"Calling test_sock_udp_send__ENOTCONN()")
    child.expect_exact(u"Calling test_sock_udp_send__socketed_no_local_no_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__socketed_no_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__socketed_no_local()")
    child.expect_exact(u"Calling test_sock_udp_send__socketed()")
    child.expect_exact(u"Calling test_sock_udp_send__socketed_other_remote()")
    child.expect_exact(u"Calling test_sock_udp_send__unsocketed_no_local_no_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__unsocketed_no_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__unsocketed_no_local()")
    child.expect_exact(u"Calling test_sock_udp_send__unsocketed()")
    child.expect_exact(u"Calling test_sock_udp_send__no_sock_no_netif()")
    child.expect_exact(u"Calling test_sock_udp_send__no_sock()")
    child.expect_exact(u"ALL TESTS SUCCESSFUL")

if __name__ == "__main__":
    sys.exit(testrunner.run(testfunc))
Example #54
0
def testfunc(child):
    tap = get_bridge(os.environ["TAP"])

    lladdr_src = get_host_lladdr(tap)
    child.sendline("ifconfig")
    child.expect("HWaddr: (?P<hwaddr>[A-Fa-f:0-9]+)")
    hwaddr_dst = child.match.group("hwaddr").lower()
    child.expect("(?P<lladdr>fe80::[A-Fa-f:0-9]+)")
    lladdr_dst = child.match.group("lladdr").lower()

    def run(func):
        if child.logfile == sys.stdout:
            func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
        else:
            try:
                func(child, tap, hwaddr_dst, lladdr_dst, lladdr_src)
                print(".", end="", flush=True)
            except Exception as e:
                print("FAILED")
                raise e

    run(test_empty_hop_by_hop_opt_wo_register)
    run(test_empty_hop_by_hop_opt_w_register)
    run(test_empty_duplicate_hop_by_hop_opt)
    run(test_empty_non_first_hop_by_hop_opt)
    run(test_empty_duplicate_non_first_hop_by_hop_opt)
    run(test_empty_routing_header_wo_register)
    run(test_empty_routing_header_w_register)
    run(test_empty_fragment_header_wo_register)
    run(test_empty_fragment_header_w_register)
    run(test_empty_dest_opt_wo_register)
    run(test_empty_dest_opt_w_register)
    # check various registrations with recommended order to validate parsing
    # (recommended order, see https://tools.ietf.org/html/rfc8200#section-4.1)
    run(test_empty_mixed1_w_hop_opt_registered)
    run(test_empty_mixed1_w_rt_hdr_registered)
    run(test_empty_mixed1_w_frag_hdr_registered)
    run(test_empty_mixed1_w_dest_opt_registered)
    # other orders SHOULD also be parsed (and since checking the order is more
    # complicated we are able to do that)
    run(test_empty_mixed2_w_hop_opt_registered)
    run(test_empty_mixed2_w_rt_hdr_registered)
    run(test_empty_mixed2_w_frag_hdr_registered)
    run(test_empty_mixed2_w_dest_opt_registered)
    print("SUCCESS")