def test_05_delete_department(self, httpcode, success, code1, message):
     response_del = self.depart_api.delete_department(
         app.Headers, app.depat_id)
     # 打印日志
     logging.info("返回数据为:{}".format(response_del.json()))
     print("删除模块返回数据:", response_del.json())
     # 断言
     assert_test(httpcode, success, code1, message, response_del, self)
 def test_03_check_department(self, httpcode, success, code1, message):
     response_check = self.depart_api.check_department(
         app.Headers, app.depat_id)
     # 打印日志
     logging.info("返回数据为:{}".format(response_check.json()))
     print("添加的员工信息为:", response_check.json())
     # 断言
     assert_test(httpcode, success, code1, message, response_check, self)
 def test_02_add_department(self, name, code, manager, introduce, httpcode,
                            success, code1, message):
     print("name={},code={},manager={},introduce={}".format(
         name, code, manager, introduce))
     response_add = self.depart_api.add_department(app.Headers, name, code,
                                                   manager, introduce)
     # 打印日志
     logging.info("返回数据为:{}".format(response_add.json()))
     print("添加部门返回的数据:", response_add.json())
     # 断言
     assert_test(httpcode, success, code1, message, response_add, self)
     # 通过全局变量获取添加员工的id,这样进行下面的操作才可以通过id进行访问
     app.depat_id = response_add.json().get("data").get("id")
 def test_01_login(self):
     json = {"mobile": "13800000002", "password": "******"}
     response = self.depart_api.login_ihrm(json)
     # 断言
     logging.info("返回数据为:{}".format(response.json()))
     print("输入数据为:", json)
     assert_test(200, True, 10000, "操作成功", response, self)
     # 获取令牌
     token = response.json().get("data")
     # 通过全局变量来获取token,要导入app文件
     app.Headers = {
         "Content-Type": "application/json",
         "Authorization": token
     }
示例#5
0
    def test_routes(self, all_routes, verbose=True, global_fail=True):
        """
        Check the presence of all optimal routes.
        """
        result = True

        # Caution: all_routes directly relies on the layout of the netlab mesh.
        #
        # The routes are organized into a dictionary with nodes as keys and
        # the expected routes as values:
        # all_routes = {
        #     <where_from>: [
        #                 (<where_to>, <price>, <next_hop>),
        #                 [...]
        #             ],
        #     [...]
        # }

        for node, routes in all_routes.items():
            for route in routes:
                desc = (
                    "Optimal route from node {} ({}) " +
                    "to {} ({}) with next-hop {} ({}) and price {}").format(
                        node.id, node.revision, route[0].id, route[0].revision,
                        route[2].id, route[2].revision, route[1])
                result = result and assert_test(node.has_route(
                    *route, verbose=verbose),
                                                desc,
                                                verbose=verbose,
                                                global_fail=global_fail)
        return result
    def test_04_put_department(self, name, code, manager, introduce, httpcode,
                               success, code1, message):
        # 修改的数据
        json = {
            "name": name,
            "code": code,
            "manager": manager,
            "introduce": introduce
        }
        response_put = self.depart_api.put_department(app.Headers,
                                                      app.depat_id, json)
        # 打印日志
        logging.info("返回数据为:{}".format(response_put.json()))
        print("修改的数据为:", json)
        print("修改返回数据", response_put.json())

        # 断言
        assert_test(httpcode, success, code1, message, response_put, self)
示例#7
0
 def test_reach_all(self, PING6, verbose=True, global_fail=True):
     for i in self.nodes.values():
         for j in self.nodes.values():
             if not assert_test(self.test_reach(i, j, PING6),
                                "Reachability " +
                                "from node {} ({}) to {} ({})".format(
                                    i.id, i.revision, j.id, j.revision),
                                verbose=verbose,
                                global_fail=global_fail):
                 return False
     return True
示例#8
0
 def test_exit_reach_all(self, verbose=True, global_fail=True):
     exit_internal_ip = get_rita_settings(
         self.exit_id)["exit_network"]["own_internal_ip"]
     for node in self.nodes.values():
         if node.id == self.exit_id:
             continue
         if not assert_test(
                 self.test_exit_reach(node, exit_internal_ip),
                 "Exit Reachability " +
                 "from node {} ({})".format(node.id, node.revision),
                 verbose=verbose,
                 global_fail=global_fail):
             return False
     return True
示例#9
0
    def test_endpoints_all(self, VERBOSE):
        for node in self.nodes.values():

            # We don't expect the exit to work the same as others
            if node.id == self.exit_id:
                # Exit-specific stuff
                continue

            print(
                colored("====== Endpoints for node {} ======".format(node.id),
                        "green"))

            # /neighbors
            if VERBOSE:
                print(colored("Hitting /neighbors:", "green"))

            result = subprocess.Popen(shlex.split(
                "ip netns exec " +
                "netlab-{} curl -sfg6 [::1]:4877/neighbors".format(node.id)),
                                      stdout=subprocess.PIPE)
            assert_test(not result.wait(), "curl-ing /neighbors")
            stdout = result.stdout.read().decode('utf-8')
            try:
                print("Received neighbors:")
                if VERBOSE:
                    neighbors = json.loads(stdout)
                    pprint(neighbors)
                else:
                    print(stdout)
            except ValueError as e:
                print('Unable to decode JSON {!r}: {}'.format(stdout, e))
                assert_test(False, "Decoding the neighbors JSON")

            # /exits
            if VERBOSE:
                print(colored("Hitting /exits:", "green"))

            result = subprocess.Popen(shlex.split(
                "ip netns exec " +
                "netlab-{} curl -sfg6 [::1]:4877/exits".format(node.id)),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            assert_test(not result.wait(), "curl-ing /exits")
            stdout = result.stdout.read().decode('utf-8')
            try:
                print("Received exits:")
                if VERBOSE:
                    exits = json.loads(stdout)
                    pprint(exits)
                else:
                    print(stdout)
            except ValueError as e:
                print('Unable to decode JSON {!r}: {}'.format(stdout, e))
                assert_test(False, "Decoding the exits JSON")

            # /info
            if VERBOSE:
                print(colored("Hitting /info:", "green"))

            result = subprocess.Popen(shlex.split(
                "ip netns exec " +
                "netlab-{} curl -sfg6 [::1]:4877/info".format(node.id)),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            assert_test(not result.wait(), "curl-ing /info")
            stdout = result.stdout.read().decode('utf-8')
            try:
                print("Received info:")
                if VERBOSE:
                    info = json.loads(stdout)
                    pprint(info)
                else:
                    print(stdout)
            except ValueError as e:
                print('Unable to decode JSON {!r}: {}'.format(stdout, e))
                assert_test(False, "Decoding the info JSON")

            # /settings
            if VERBOSE:
                print(colored("Hitting /settings:", "green"))

            result = subprocess.Popen(shlex.split(
                "ip netns exec " +
                "netlab-{} curl -sfg6 [::1]:4877/settings".format(node.id)),
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            assert_test(not result.wait(), "curl-ing /settings")
            stdout = result.stdout.read().decode('utf-8')
            try:
                print("Received settings:")
                if VERBOSE:
                    settings = json.loads(stdout)
                    pprint(settings)
                else:
                    print(stdout)
            except ValueError as e:
                print('Unable to decode JSON {!r}: {}'.format(stdout, e))
                assert_test(False, "Decoding the settings JSON")
示例#10
0
def main():
    if NODES is None or 'None' in NODES:
        nodes = 7
        (COMPAT_LAYOUTS, all_routes, traffic_test_pairs, world, EXIT_NAMESPACE,
         EXIT_ID, GATEWAY_NAMESPACE, GATEWAY_ID) = setup_seven_node_config()
    else:
        nodes = int(NODES)
        (COMPAT_LAYOUTS, all_routes, traffic_test_pairs, world, EXIT_NAMESPACE,
         EXIT_ID, GATEWAY_NAMESPACE,
         GATEWAY_ID) = setup_arbitrary_node_config(nodes)

    COMPAT_LAYOUTS["random"] = [
        'a' if random.randint(0, 1) else 'b' for _ in range(7)
    ]

    if VERBOSE:
        print("Random compat test layout: {}".format(COMPAT_LAYOUTS["random"]))

    world.create(VERBOSE, COMPAT_LAYOUT, COMPAT_LAYOUTS, RITA, RITA_EXIT,
                 DIR_A, DIR_B, RITA_A, RITA_EXIT_A, RITA_B, RITA_EXIT_B,
                 NETWORK_LAB, BABELD, POSTGRES_DATABASE, POSTGRES_USER,
                 POSTGRES_CONFIG, POSTGRES_BIN, INITDB_BIN, EXIT_NAMESPACE,
                 EXIT_SETTINGS, dname)

    print("Waiting for network to stabilize")
    start_time = time.time()

    interval = INITIAL_POLL_INTERVAL

    if DEBUG:
        print("Debug mode active, examine the mesh and press y to continue " +
              "with the tests or anything else to exit")
        choice = input()
        if choice != 'y':
            sys.exit(0)

    # While we're before convergence deadline
    while (time.time() - start_time) <= CONVERGENCE_DELAY:
        all_reachable = world.test_reach_all(PING6,
                                             verbose=False,
                                             global_fail=False)
        routes_ok = world.test_routes(all_routes,
                                      verbose=False,
                                      global_fail=False)
        if all_reachable and routes_ok:
            break  # We converged!
        time.sleep(interval)  # Let's check again after a delay
        interval *= BACKOFF_FACTOR
        if VERBOSE is not None:
            print("%.2fs/%.2fs (going to sleep for %.2fs)" %
                  (time.time() - start_time, CONVERGENCE_DELAY, interval))

    print("Test reachabibility and optimum routes...")
    time.sleep(120)

    duration = time.time() - start_time

    # Test (and fail if necessary) for real and print stats on success
    if world.test_reach_all(PING6) and world.test_routes(all_routes):
        print(("Converged in " + colored("%.2f seconds", "green")) % duration)
    else:
        print(
            ("No convergence after more than " + colored("%d seconds", "red") +
             ", quitting...") % CONVERGENCE_DELAY)
        sys.exit(1)

    print("Waiting for clients to get info from exits")
    time.sleep(5)

    for k, v in world.nodes.items():
        if k != world.exit_id:
            register_to_exit(v)

    print("waiting for emails to be sent")
    time.sleep(15)

    for k, v in world.nodes.items():
        if k != world.exit_id:
            email_verif(v)

    time.sleep(15)

    world.test_endpoints_all(VERBOSE)

    if DEBUG:
        print("Debug mode active, examine the mesh and press y to continue " +
              "with the tests or anything else to exit")
        choice = input()
        if choice != 'y':
            sys.exit(0)

    world.test_exit_reach_all(global_fail=True)

    world.test_traffic(traffic_test_pairs, TIME, SPEED)

    # wait a few seconds after traffic generation for all nodes to update their debts
    time.sleep(10)
    traffic = world.get_debts()
    print("Test post-traffic blanace agreement...")
    world.test_debts_reciprocal_matching(traffic)
    world.test_debts_values(traffic_test_pairs, TIME, SPEED, traffic,
                            all_routes, EXIT_ID, world.exit_price)

    print("Check that tunnels have not been suspended")

    for id in world.nodes:
        assert_test(
            not check_log_contains("rita-n{}.log".format(id),
                                   "suspending forwarding"),
            "Suspension of {}".format(id))

    assert_test(
        check_log_contains("rita-n{}.log".format(GATEWAY_ID),
                           "We are a gateway!, Acting accordingly"),
        "Successful gateway/exit detection")

    if DEBUG:
        print("Debug mode active, examine the mesh after tests and press " +
              "Enter to exit")
        input()

    teardown()

    print("done... exiting")

    if TEST_PASSES:
        print("All Rita tests passed!!")
        exit(0)
    else:
        print("Rita tests have failed :(")
        exit(1)