def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     
     
     
     # create a LB
     if self.TESTS_CONFIG_READYMADE_LB_ID is None:
         
         # search a switch
         print('作成済みのルータ+スイッチを検索しています...')
         swytches = api.swytch.with_name_like('saklient-lb-attached').limit(1).find()
         if 0 < len(swytches):
             swytch = swytches[0]
         else:
             print('ルータ+スイッチを作成しています...')
             router = api.router.create()
             router.name = 'saklient-lb-attached'
             router.band_width_mbps = 100
             router.network_mask_len = 28
             router.save()
             
             print('ルータ+スイッチの作成完了を待機しています...')
             if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
             swytch = router.get_swytch()
         
         self.assertIsInstance(swytch, Swytch)
         self.assertTrue(len(swytch.ipv4_nets) > 0)
         net = swytch.ipv4_nets[0]
         print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))
         
         # create a loadbalancer
         print('ロードバランサを作成しています...')
         vrid = 123
         real_ip1 = Util.long2ip(Util.ip2long(net.default_route) + 3)
         real_ip2 = Util.long2ip(Util.ip2long(net.default_route) + 4)
         lb = api.appliance.create_load_balancer(swytch, vrid, [real_ip1, real_ip2], True)
         
         def test_required():
             lb.save()
         self.assertRaises(SaklientException, test_required)
         # Requiredフィールドが未set時は SaklientException がスローされなければなりません
         lb.name = name
         lb.description = ''
         lb.tags = [tag]
         lb.save()
         
         lb.reload()
         self.assertEqual(lb.default_route, net.default_route)
         self.assertEqual(lb.mask_len, net.mask_len)
         self.assertEqual(lb.vrid, vrid)
         self.assertEqual(lb.swytch_id, swytch.id)
         
         # wait the LB becomes up
         print('ロードバランサの起動を待機しています...')
         if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')
     
     else:
         
         lb = api.appliance.get_by_id(self.TESTS_CONFIG_READYMADE_LB_ID)
         self.assertIsInstance(lb, LoadBalancer)
         swytch = lb.get_swytch()
         self.assertIsInstance(swytch, Swytch)
         net = swytch.ipv4_nets[0]
         self.assertIsInstance(net, Ipv4Net)
         print('%s/%d -> %s' % (net.address, net.mask_len, net.default_route))
     
     
     
     # clear virtual ips
     
     lb.clear_virtual_ips()
     lb.save()
     lb.reload()
     self.assertEqual(len(lb.virtual_ips), 0)
     
     
     
     # setting virtual ips test 1
     
     vip1Ip     = long2ip(ip2long(net.default_route) + 5)
     vip1SrvIp1 = long2ip(ip2long(net.default_route) + 6)
     vip1SrvIp2 = long2ip(ip2long(net.default_route) + 7)
     vip1SrvIp3 = long2ip(ip2long(net.default_route) + 8)
     vip1SrvIp4 = long2ip(ip2long(net.default_route) + 9)
     
     lb.add_virtual_ip({
         'vip': vip1Ip,
         'port': 80,
         'delay': 15,
         'servers': [
             { 'ip':vip1SrvIp1, 'port':80, 'protocol':'http', 'path_to_check':'/index.html', 'response_expected':200 },
             { 'ip':vip1SrvIp2, 'port':80, 'protocol':'https', 'path_to_check':'/', 'response_expected':200 },
             { 'ip':vip1SrvIp3, 'port':80, 'protocol':'tcp' }
         ]
     })
     
     vip2Ip     = long2ip(ip2long(net.default_route) + 10)
     vip2SrvIp1 = long2ip(ip2long(net.default_route) + 11)
     vip2SrvIp2 = long2ip(ip2long(net.default_route) + 12)
     
     vip2 = lb.add_virtual_ip()
     vip2.virtual_ip_address = vip2Ip
     vip2.port = 80
     vip2.delay_loop = 15
     vip2Srv1 = vip2.add_server()
     vip2Srv1.ip_address = vip2SrvIp1
     vip2Srv1.port = 80
     vip2Srv1.protocol = 'http'
     vip2Srv1.path_to_check = '/index.html'
     vip2Srv1.response_expected = 200
     vip2Srv2 = vip2.add_server()
     vip2Srv2.ip_address = vip2SrvIp2
     vip2Srv2.port = 80
     vip2Srv2.protocol = 'tcp'
     lb.save()
     lb.reload()
     
     self.assertEqual(len(lb.virtual_ips), 2)
     self.assertEqual(lb.virtual_ips[0].virtual_ip_address, vip1Ip)
     self.assertEqual(len(lb.virtual_ips[0].servers), 3)
     self.assertEqual(lb.virtual_ips[0].servers[0].ip_address, vip1SrvIp1)
     self.assertEqual(lb.virtual_ips[0].servers[0].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[0].protocol, 'http')
     self.assertEqual(lb.virtual_ips[0].servers[0].path_to_check, '/index.html')
     self.assertEqual(lb.virtual_ips[0].servers[0].response_expected, 200)
     self.assertEqual(lb.virtual_ips[0].servers[1].ip_address, vip1SrvIp2)
     self.assertEqual(lb.virtual_ips[0].servers[1].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[1].protocol, 'https')
     self.assertEqual(lb.virtual_ips[0].servers[1].path_to_check, '/')
     self.assertEqual(lb.virtual_ips[0].servers[1].response_expected, 200)
     self.assertEqual(lb.virtual_ips[0].servers[2].ip_address, vip1SrvIp3)
     self.assertEqual(lb.virtual_ips[0].servers[2].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[2].protocol, 'tcp')
     self.assertEqual(lb.virtual_ips[1].virtual_ip_address, vip2Ip)
     self.assertEqual(len(lb.virtual_ips[1].servers), 2)
     self.assertEqual(lb.virtual_ips[1].servers[0].ip_address, vip2SrvIp1)
     self.assertEqual(lb.virtual_ips[1].servers[0].port, 80)
     self.assertEqual(lb.virtual_ips[1].servers[0].protocol, 'http')
     self.assertEqual(lb.virtual_ips[1].servers[0].path_to_check, '/index.html')
     self.assertEqual(lb.virtual_ips[1].servers[0].response_expected, 200)
     self.assertEqual(lb.virtual_ips[1].servers[1].ip_address, vip2SrvIp2)
     self.assertEqual(lb.virtual_ips[1].servers[1].port, 80)
     self.assertEqual(lb.virtual_ips[1].servers[1].protocol, 'tcp')
     
     
     
     # setting virtual ips test 2
     
     lb.get_virtual_ip_by_address(vip1Ip).add_server({
         'ip': vip1SrvIp4,
         'port': 80,
         'protocol': 'ping'
     })
     lb.save()
     lb.reload()
     
     self.assertEqual(len(lb.virtual_ips), 2)
     self.assertEqual(len(lb.virtual_ips[0].servers), 4)
     self.assertEqual(lb.virtual_ips[0].servers[3].ip_address, vip1SrvIp4)
     self.assertEqual(lb.virtual_ips[0].servers[3].port, 80)
     self.assertEqual(lb.virtual_ips[0].servers[3].protocol, 'ping')
     self.assertEqual(len(lb.virtual_ips[1].servers), 2)
     
     
     
     # checking status
     
     lb.reload_status()
     for vip in lb.virtual_ips:
         print('  vip %s:%s every %ssec(s)' % (vip.virtual_ip_address, vip.port, vip.delay_loop))
         for server in vip.servers:
             print('    [%s(%s)]' % (server.status, server.active_connections), end='')
             print(' server %s://%s' % (server.protocol, server.ip_address), end='')
             if server.port: print(':%d' % (server.port), end='')
             if server.path_to_check: print(server.path_to_check, end='')
             print(' answers', end='')
             if server.response_expected: print(' %d' % (server.response_expected), end='')
             print('')
             self.assertEqual(server.status, 'down')
     
     
     
     if not self.TESTS_CONFIG_READYMADE_LB_ID:
         
         # stop the LB
         time.sleep(1)
         print('ロードバランサを停止しています...')
         if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')
         
         # delete the LB
         print('ロードバランサを削除しています...')
         lb.destroy()
Example #2
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
Example #3
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     mask_len = 28
     mask_len_cnt = 1<<32-mask_len
     sroute_mask_len = 28
     sroute_mask_len_cnt = 1<<32-sroute_mask_len
     
     #
     swytch = None
     if True:
         print('ルータ+スイッチの帯域プランを検索しています...')
         plans = api.product.router.find()
         min_mbps = 0x7FFFFFFF
         for plan in plans:
             self.assertIsInstance(plan, RouterPlan)
             self.assertTrue(0 < plan.band_width_mbps)
             min_mbps = min(plan.band_width_mbps, min_mbps)
         
         print('ルータ+スイッチを作成しています...')
         router = api.router.create()
         router.name = name
         router.description = description
         router.band_width_mbps = min_mbps
         router.network_mask_len = mask_len
         router.save()
         
         print('ルータ+スイッチの作成完了を待機しています...')
         if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
         swytch = router.get_swytch()
     else:
         print('既存のルータ+スイッチを取得しています...')
         swytches = api.swytch.with_name_like('saklient-static-1').limit(1).find()
         self.assertEqual(len(swytches), 1)
         swytch = swytches[0]
     
     self.assertIsInstance(swytch, Swytch)
     self.assertEqual(len(swytch.ipv4_nets), 1)
     self.assertIsInstance(swytch.ipv4_nets[0], Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets[0].range.as_array), mask_len_cnt-5)
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 0)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-5)
     
     #
     print('サーバを作成しています...')
     server = api.server.create()
     self.assertIsInstance(server, Server)
     server.name = name
     server.description = description
     server.plan = api.product.server.get_by_spec(1, 1)
     server.save()
     self.assertTrue(0 < int(server.id))
      
     #
     print('インタフェースを増設しています...')
     iface = server.add_iface()
     self.assertIsInstance(iface, Iface)
     self.assertTrue(0 < int(iface.id))
     
     #
     print('インタフェースをルータ+スイッチに接続しています...')
     iface.connect_to_swytch(swytch)
     
     #
     print('インタフェースにIPアドレスを設定しています...')
     iface.user_ip_address = swytch.ipv4_nets[0].range.as_array[1]
     iface.save()
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 1)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-6)
     
     #
     print('ルータ+スイッチの帯域プランを変更しています...')
     router_id_before = swytch.router.id
     swytch.change_plan(500 if swytch.router.band_width_mbps==100 else 100)
     self.assertNotEqual(swytch.router.id, router_id_before)
     
     #
     print('ルータ+スイッチにIPv6ネットワークを割り当てています...')
     v6net = swytch.add_ipv6_net()
     self.assertIsInstance(v6net, Ipv6Net)
     self.assertEqual(len(swytch.ipv6_nets), 1)
     
     #
     print('ルータ+スイッチにスタティックルートを割り当てています...')
     net0 = swytch.ipv4_nets[0]
     next_hop = Util.long2ip(Util.ip2long(net0.address) + 4)
     sroute = swytch.add_static_route(28, next_hop)
     self.assertIsInstance(sroute, Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets), 2)
     self.assertEqual(len(swytch.ipv4_nets[1].range.as_array), sroute_mask_len_cnt)
     
     #
     for i in range(len(swytch.ipv4_nets) - 1, 0, -1):
         print('ルータ+スイッチからスタティックルートの割当を解除しています...')
         net = swytch.ipv4_nets[i]
         swytch.remove_static_route(net)
     
     #
     if 0 < len(swytch.ipv6_nets):
         print('ルータ+スイッチからIPv6ネットワークの割当を解除しています...')
         swytch.remove_ipv6_net()
     
     #
     print('サーバを削除しています...')
     server.destroy()
Example #4
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
     # 未定義または読み取り専用フィールドへのset時は AttributeError がスローされなければなりません
     
     #
     self.assertEqual(Util.ip2long('0.0.0.0'), 0)
     self.assertEqual(Util.ip2long('127.255.255.255'), 0x7FFFFFFF)
     self.assertEqual(Util.ip2long('128.0.0.0'), 0x80000000)
     self.assertEqual(Util.ip2long('255.255.255.255'), 0xFFFFFFFF)
     self.assertEqual(Util.ip2long('222.173.190.239'), 0xDEADBEEF)
     #
     self.assertEqual(Util.long2ip(0), '0.0.0.0')
     self.assertEqual(Util.long2ip(0x7FFFFFFF), '127.255.255.255')
     self.assertEqual(Util.long2ip(0x80000000), '128.0.0.0')
     self.assertEqual(Util.long2ip(0xFFFFFFFF), '255.255.255.255')
     self.assertEqual(Util.long2ip(0xDEADBEEF), '222.173.190.239')
     self.assertEqual(Util.long2ip(Util.ip2long('127.255.255.255') + 1), '128.0.0.0')
     #
     self.assertIsNone(Util.ip2long(None))
     self.assertIsNone(Util.ip2long(0))
     self.assertIsNone(Util.ip2long(''))
     self.assertIsNone(Util.ip2long('x'))
     self.assertIsNone(Util.ip2long('0.0.0'))
     self.assertIsNone(Util.ip2long('0.0.0.x'))
     self.assertIsNone(Util.ip2long('0.0.0.0.0'))
     self.assertIsNone(Util.ip2long('255.255.255.256'))
     self.assertIsNone(Util.ip2long('256.255.255.255'))
     self.assertIsNone(Util.long2ip(None))
     self.assertEqual(Util.long2ip('0'), '0.0.0.0')
     self.assertEqual(Util.long2ip(Util.ip2long('0.0.0.0') - 1), '255.255.255.255')
     self.assertIsNone(Util.long2ip(Util.ip2long('255.255.255.255') + 1))
Example #5
0
 def test_should_be_cruded(self):
     
     # load config file
     root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     test_ok_file = root + '/testok'
     if not os.path.exists(test_ok_file):
         print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
         sys.exit(0)
     
     config_file = root + '/config.sh'
     self.assertTrue(os.path.exists(config_file)) # config_file を作成してください。
     
     config = {}
     fh = open(config_file, "r")
     for line in fh:
         m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
         if m is None: continue
         key = m.group(1)
         value = m.group(2)
         value = re.sub("'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)", lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4), value)
         config[key] = value
     fh.close()
     
     self.assertIn('SACLOUD_TOKEN', config)
     self.assertIn('SACLOUD_SECRET', config)
     self.assertIn('SACLOUD_ZONE', config)
     
     # authorize
     api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'], config['SACLOUD_ZONE'])
     self.assertIsInstance(api, API)
     
     
     
     # should be CRUDed
     name = '!python_test-' + datetime.now().strftime('%Y%m%d_%H%M%S') + '-' + ''.join([random.choice(string.ascii_letters + string.digits) for i in range(8)])
     description = 'This instance was created by saklient.python test'
     tag = 'saklient-test'
     mask_len = 28
     mask_len_cnt = 1<<32-mask_len
     sroute_mask_len = 28
     sroute_mask_len_cnt = 1<<32-sroute_mask_len
     
     #
     swytch = None
     if True:
         print('ルータ+スイッチの帯域プランを検索しています...')
         plans = api.product.router.find()
         min_mbps = 0x7FFFFFFF
         for plan in plans:
             self.assertIsInstance(plan, RouterPlan)
             self.assertTrue(0 < plan.band_width_mbps)
             min_mbps = min(plan.band_width_mbps, min_mbps)
         
         print('ルータ+スイッチを作成しています...')
         router = api.router.create()
         router.name = name
         router.description = description
         router.band_width_mbps = min_mbps
         router.network_mask_len = mask_len
         router.save()
         
         print('ルータ+スイッチの作成完了を待機しています...')
         if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
         swytch = router.get_swytch()
     else:
         print('既存のルータ+スイッチを取得しています...')
         swytches = api.swytch.with_name_like('saklient-static-1').limit(1).find()
         self.assertEqual(len(swytches), 1)
         swytch = swytches[0]
     
     self.assertIsInstance(swytch, Swytch)
     self.assertEqual(len(swytch.ipv4_nets), 1)
     self.assertIsInstance(swytch.ipv4_nets[0], Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets[0].range.as_array), mask_len_cnt-5)
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 0)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-5)
     
     #
     print('サーバを作成しています...')
     server = api.server.create()
     self.assertIsInstance(server, Server)
     server.name = name
     server.description = description
     server.plan = api.product.server.get_by_spec(1, 1)
     server.save()
     self.assertTrue(0 < int(server.id))
      
     #
     print('インタフェースを増設しています...')
     iface = server.add_iface()
     self.assertIsInstance(iface, Iface)
     self.assertTrue(0 < int(iface.id))
     
     #
     print('インタフェースをルータ+スイッチに接続しています...')
     iface.connect_to_swytch(swytch)
     
     #
     print('インタフェースにIPアドレスを設定しています...')
     iface.user_ip_address = swytch.ipv4_nets[0].range.as_array[1]
     iface.save()
     self.assertEqual(len(swytch.collect_used_ipv4_addresses()), 1)
     self.assertEqual(len(swytch.collect_unused_ipv4_addresses()), mask_len_cnt-6)
     
     #
     print('ルータ+スイッチの帯域プランを変更しています...')
     router_id_before = swytch.router.id
     swytch.change_plan(500 if swytch.router.band_width_mbps==100 else 100)
     self.assertNotEqual(swytch.router.id, router_id_before)
     
     #
     print('ルータ+スイッチにIPv6ネットワークを割り当てています...')
     v6net = swytch.add_ipv6_net()
     self.assertIsInstance(v6net, Ipv6Net)
     self.assertEqual(len(swytch.ipv6_nets), 1)
     
     #
     print('ルータ+スイッチにスタティックルートを割り当てています...')
     net0 = swytch.ipv4_nets[0]
     next_hop = Util.long2ip(Util.ip2long(net0.address) + 4)
     sroute = swytch.add_static_route(28, next_hop)
     self.assertIsInstance(sroute, Ipv4Net)
     self.assertEqual(len(swytch.ipv4_nets), 2)
     self.assertEqual(len(swytch.ipv4_nets[1].range.as_array), sroute_mask_len_cnt)
     
     #
     for i in range(len(swytch.ipv4_nets) - 1, 0, -1):
         print('ルータ+スイッチからスタティックルートの割当を解除しています...')
         net = swytch.ipv4_nets[i]
         swytch.remove_static_route(net)
     
     #
     if 0 < len(swytch.ipv6_nets):
         print('ルータ+スイッチからIPv6ネットワークの割当を解除しています...')
         swytch.remove_ipv6_net()
     
     #
     print('サーバを削除しています...')
     server.destroy()
    def test_should_be_cruded(self):

        # load config file
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        test_ok_file = root + '/testok'
        if not os.path.exists(test_ok_file):
            print("詳細テストを行うには " + test_ok_file + " をtouchしてください。")
            sys.exit(0)

        config_file = root + '/config.sh'
        self.assertTrue(os.path.exists(config_file))  # config_file を作成してください。

        config = {}
        fh = open(config_file, "r")
        for line in fh:
            m = re.search("^\\s*export\\s+(\\w+)\\s*=\\s*(.+?)\\s*$", line)
            if m is None: continue
            key = m.group(1)
            value = m.group(2)
            value = re.sub(
                "'([^']*)'|\"([^\"]*)\"|\\\\(.)|(.)",
                lambda m: m.group(1) or m.group(2) or m.group(3) or m.group(4),
                value)
            config[key] = value
        fh.close()

        self.assertIn('SACLOUD_TOKEN', config)
        self.assertIn('SACLOUD_SECRET', config)
        self.assertIn('SACLOUD_ZONE', config)

        # authorize
        api = API.authorize(config['SACLOUD_TOKEN'], config['SACLOUD_SECRET'],
                            config['SACLOUD_ZONE'])
        self.assertIsInstance(api, API)

        # should be CRUDed
        name = '!python_test-' + datetime.now().strftime(
            '%Y%m%d_%H%M%S') + '-' + ''.join([
                random.choice(string.ascii_letters + string.digits)
                for i in range(8)
            ])
        description = 'This instance was created by saklient.python test'
        tag = 'saklient-test'

        # create a LB
        if self.TESTS_CONFIG_READYMADE_LB_ID is None:

            # search a switch
            print('作成済みのルータ+スイッチを検索しています...')
            swytches = api.swytch.with_name_like('saklient-lb-attached').limit(
                1).find()
            if 0 < len(swytches):
                swytch = swytches[0]
            else:
                print('ルータ+スイッチを作成しています...')
                router = api.router.create()
                router.name = 'saklient-lb-attached'
                router.band_width_mbps = 100
                router.network_mask_len = 28
                router.save()

                print('ルータ+スイッチの作成完了を待機しています...')
                if not router.sleep_while_creating(): fail('ルータが正常に作成されません')
                swytch = router.get_swytch()

            self.assertIsInstance(swytch, Swytch)
            self.assertTrue(len(swytch.ipv4_nets) > 0)
            net = swytch.ipv4_nets[0]
            print('%s/%d -> %s' %
                  (net.address, net.mask_len, net.default_route))

            # create a loadbalancer
            print('ロードバランサを作成しています...')
            vrid = 123
            real_ip1 = Util.long2ip(Util.ip2long(net.default_route) + 3)
            real_ip2 = Util.long2ip(Util.ip2long(net.default_route) + 4)
            lb = api.appliance.create_load_balancer(swytch, vrid,
                                                    [real_ip1, real_ip2], True)

            def test_required():
                lb.save()

            self.assertRaises(SaklientException, test_required)
            # Requiredフィールドが未set時は SaklientException がスローされなければなりません
            lb.name = name
            lb.description = ''
            lb.tags = [tag]
            lb.save()

            lb.reload()
            self.assertEqual(lb.default_route, net.default_route)
            self.assertEqual(lb.mask_len, net.mask_len)
            self.assertEqual(lb.vrid, vrid)
            self.assertEqual(lb.swytch_id, swytch.id)

            # wait the LB becomes up
            print('ロードバランサの起動を待機しています...')
            if not lb.sleep_until_up(): fail('ロードバランサが正常に起動しません')

        else:

            lb = api.appliance.get_by_id(self.TESTS_CONFIG_READYMADE_LB_ID)
            self.assertIsInstance(lb, LoadBalancer)
            swytch = lb.get_swytch()
            self.assertIsInstance(swytch, Swytch)
            net = swytch.ipv4_nets[0]
            self.assertIsInstance(net, Ipv4Net)
            print('%s/%d -> %s' %
                  (net.address, net.mask_len, net.default_route))

        # clear virtual ips

        lb.clear_virtual_ips()
        lb.save()
        lb.reload()
        self.assertEqual(len(lb.virtual_ips), 0)

        # setting virtual ips test 1

        vip1Ip = long2ip(ip2long(net.default_route) + 5)
        vip1SrvIp1 = long2ip(ip2long(net.default_route) + 6)
        vip1SrvIp2 = long2ip(ip2long(net.default_route) + 7)
        vip1SrvIp3 = long2ip(ip2long(net.default_route) + 8)
        vip1SrvIp4 = long2ip(ip2long(net.default_route) + 9)

        lb.add_virtual_ip({
            'vip':
            vip1Ip,
            'port':
            80,
            'delay':
            15,
            'servers': [{
                'ip': vip1SrvIp1,
                'port': 80,
                'protocol': 'http',
                'path_to_check': '/index.html',
                'response_expected': 200
            }, {
                'ip': vip1SrvIp2,
                'port': 80,
                'protocol': 'https',
                'path_to_check': '/',
                'response_expected': 200
            }, {
                'ip': vip1SrvIp3,
                'port': 80,
                'protocol': 'tcp'
            }]
        })

        vip2Ip = long2ip(ip2long(net.default_route) + 10)
        vip2SrvIp1 = long2ip(ip2long(net.default_route) + 11)
        vip2SrvIp2 = long2ip(ip2long(net.default_route) + 12)

        vip2 = lb.add_virtual_ip()
        vip2.virtual_ip_address = vip2Ip
        vip2.port = 80
        vip2.delay_loop = 15
        vip2Srv1 = vip2.add_server()
        vip2Srv1.ip_address = vip2SrvIp1
        vip2Srv1.port = 80
        vip2Srv1.protocol = 'http'
        vip2Srv1.path_to_check = '/index.html'
        vip2Srv1.response_expected = 200
        vip2Srv2 = vip2.add_server()
        vip2Srv2.ip_address = vip2SrvIp2
        vip2Srv2.port = 80
        vip2Srv2.protocol = 'tcp'
        lb.save()
        lb.reload()

        self.assertEqual(len(lb.virtual_ips), 2)
        self.assertEqual(lb.virtual_ips[0].virtual_ip_address, vip1Ip)
        self.assertEqual(len(lb.virtual_ips[0].servers), 3)
        self.assertEqual(lb.virtual_ips[0].servers[0].ip_address, vip1SrvIp1)
        self.assertEqual(lb.virtual_ips[0].servers[0].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[0].protocol, 'http')
        self.assertEqual(lb.virtual_ips[0].servers[0].path_to_check,
                         '/index.html')
        self.assertEqual(lb.virtual_ips[0].servers[0].response_expected, 200)
        self.assertEqual(lb.virtual_ips[0].servers[1].ip_address, vip1SrvIp2)
        self.assertEqual(lb.virtual_ips[0].servers[1].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[1].protocol, 'https')
        self.assertEqual(lb.virtual_ips[0].servers[1].path_to_check, '/')
        self.assertEqual(lb.virtual_ips[0].servers[1].response_expected, 200)
        self.assertEqual(lb.virtual_ips[0].servers[2].ip_address, vip1SrvIp3)
        self.assertEqual(lb.virtual_ips[0].servers[2].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[2].protocol, 'tcp')
        self.assertEqual(lb.virtual_ips[1].virtual_ip_address, vip2Ip)
        self.assertEqual(len(lb.virtual_ips[1].servers), 2)
        self.assertEqual(lb.virtual_ips[1].servers[0].ip_address, vip2SrvIp1)
        self.assertEqual(lb.virtual_ips[1].servers[0].port, 80)
        self.assertEqual(lb.virtual_ips[1].servers[0].protocol, 'http')
        self.assertEqual(lb.virtual_ips[1].servers[0].path_to_check,
                         '/index.html')
        self.assertEqual(lb.virtual_ips[1].servers[0].response_expected, 200)
        self.assertEqual(lb.virtual_ips[1].servers[1].ip_address, vip2SrvIp2)
        self.assertEqual(lb.virtual_ips[1].servers[1].port, 80)
        self.assertEqual(lb.virtual_ips[1].servers[1].protocol, 'tcp')

        # setting virtual ips test 2

        lb.get_virtual_ip_by_address(vip1Ip).add_server({
            'ip': vip1SrvIp4,
            'port': 80,
            'protocol': 'ping'
        })
        lb.save()
        lb.reload()

        self.assertEqual(len(lb.virtual_ips), 2)
        self.assertEqual(len(lb.virtual_ips[0].servers), 4)
        self.assertEqual(lb.virtual_ips[0].servers[3].ip_address, vip1SrvIp4)
        self.assertEqual(lb.virtual_ips[0].servers[3].port, 80)
        self.assertEqual(lb.virtual_ips[0].servers[3].protocol, 'ping')
        self.assertEqual(len(lb.virtual_ips[1].servers), 2)

        # checking status

        lb.reload_status()
        for vip in lb.virtual_ips:
            print('  vip %s:%s every %ssec(s)' %
                  (vip.virtual_ip_address, vip.port, vip.delay_loop))
            for server in vip.servers:
                msg = '    [%s(%s)]' % (server.status,
                                        server.active_connections)
                msg += ' server %s://%s' % (server.protocol, server.ip_address)
                if server.port: msg += ':%d' % (server.port)
                if server.path_to_check: msg += server.path_to_check
                msg += ' answers'
                if server.response_expected:
                    msg += ' %d' % (server.response_expected)
                print(msg)
                # self.assertEqual(server.status, 'down')

        if not self.TESTS_CONFIG_READYMADE_LB_ID:

            # stop the LB
            time.sleep(1)
            print('ロードバランサを停止しています...')
            if not lb.stop().sleep_until_down(): fail('ロードバランサが正常に停止しません')

            # delete the LB
            print('ロードバランサを削除しています...')
            lb.destroy()
Example #7
0
 def test_should_access_objects_by_path(self):
     test = {}
     Util.set_by_path(test, "top", 123)
     self.assertEqual(test["top"], 123)
     Util.set_by_path(test, "first.second", 456)
     self.assertEqual(test["first"]["second"], 456)
     Util.set_by_path(test, ".weird..path", 789)
     self.assertEqual(test["weird"]["path"], 789)
     Util.set_by_path(test, "existing.None", None)
     self.assertIsNotNone(Util.get_by_path(test, "existing"))
     self.assertEqual(Util.get_by_path(test, "existing.None"), None)
     #
     self.assertEqual(Util.get_by_path(test, "top"), 123)
     self.assertEqual(Util.get_by_path(test, "first.second"), 456)
     self.assertEqual(Util.get_by_path(test, ".weird..path"), 789)
     #
     self.assertEqual(Util.get_by_path(test, "nothing"), None)
     self.assertEqual(Util.get_by_path(test, "nothing.child"), None)
     self.assertEqual(Util.get_by_path(test, "top.child"), None)
     #
     self.assertTrue(Util.exists_path(test, "top"))
     self.assertFalse(Util.exists_path(test, "top.child"))
     self.assertTrue(Util.exists_path(test, "first.second"))
     self.assertTrue(Util.exists_path(test, ".weird..path"))
     self.assertFalse(Util.exists_path(test, "nothing"))
     self.assertFalse(Util.exists_path(test, "nothing.child"))
     self.assertTrue(Util.exists_path(test, "existing"))
     self.assertTrue(Util.exists_path(test, "existing.None"))
     #
     test["first"]["second"] *= 10
     self.assertEqual(Util.get_by_path(test, "first.second"), 4560)
     
     #
     Util.validate_type(1, "int")
     Util.validate_type(1.1, "float")
     Util.validate_type(False, "bool")
     Util.validate_type("abc", "str")
     ex = SaklientException("a", "a")
     Util.validate_type(ex, "saklient.errors.saklientexception.SaklientException")
     Util.validate_type(ex, "Exception")
     
     #
     self.assertRaises(SaklientException, lambda: API.authorize("a", []))
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     self.assertRaises(TypeError, lambda: API.authorize("a"))
     # 引数の数が足りない時は TypeError がスローされなければなりません
     
     #
     def validation_test():
         server = API.authorize("a", "a").server.create()
         server.name = ["abc"]
     self.assertRaises(SaklientException, validation_test)
     # 引数の型が異なる時は SaklientException がスローされなければなりません
     
     #
     def immutable_test():
         server = API.authorize("a", "a").server.create()
         server.availability = "available"
     self.assertRaises(AttributeError, immutable_test)
     # 未定義または読み取り専用フィールドへのset時は AttributeError がスローされなければなりません
     
     #
     self.assertEqual(Util.ip2long('0.0.0.0'), 0)
     self.assertEqual(Util.ip2long('127.255.255.255'), 0x7FFFFFFF)
     self.assertEqual(Util.ip2long('128.0.0.0'), 0x80000000)
     self.assertEqual(Util.ip2long('255.255.255.255'), 0xFFFFFFFF)
     self.assertEqual(Util.ip2long('222.173.190.239'), 0xDEADBEEF)
     #
     self.assertEqual(Util.long2ip(0), '0.0.0.0')
     self.assertEqual(Util.long2ip(0x7FFFFFFF), '127.255.255.255')
     self.assertEqual(Util.long2ip(0x80000000), '128.0.0.0')
     self.assertEqual(Util.long2ip(0xFFFFFFFF), '255.255.255.255')
     self.assertEqual(Util.long2ip(0xDEADBEEF), '222.173.190.239')
     self.assertEqual(Util.long2ip(Util.ip2long('127.255.255.255') + 1), '128.0.0.0')
     #
     self.assertIsNone(Util.ip2long(None))
     self.assertIsNone(Util.ip2long(0))
     self.assertIsNone(Util.ip2long(''))
     self.assertIsNone(Util.ip2long('x'))
     self.assertIsNone(Util.ip2long('0.0.0'))
     self.assertIsNone(Util.ip2long('0.0.0.x'))
     self.assertIsNone(Util.ip2long('0.0.0.0.0'))
     self.assertIsNone(Util.ip2long('255.255.255.256'))
     self.assertIsNone(Util.ip2long('256.255.255.255'))
     self.assertIsNone(Util.long2ip(None))
     self.assertEqual(Util.long2ip('0'), '0.0.0.0')
     self.assertEqual(Util.long2ip(Util.ip2long('0.0.0.0') - 1), '255.255.255.255')
     self.assertIsNone(Util.long2ip(Util.ip2long('255.255.255.255') + 1))