def get(self):
     """Returns an available server's IP address in JSON format."""
     ip = LoadInfo.GetIdleInstanceIpAddress()
     if not ip:
         ip = ''
     self.response.out.write(json.dumps({'ipaddress': ip}))
     IpAddressRequestLog(client_ip=self.request.remote_addr,
                         server_ip=ip).put()
    def testGetIdleInstanceExcludingImmatureInstance(self):
        LoadInfo.InitializeTable()
        LoadInfo.AddInstance('test-instance1')
        LoadInfo.RegisterInstanceIpAddress('test-instance1', '1.2.3.4')
        LoadInfo.UpdateLoadInfo('test-instance1', 55)
        LoadInfo.AddInstance('test-instance2')
        LoadInfo.RegisterInstanceIpAddress('test-instance2', '5.6.7.8')
        # test-instance2 hasn't yet reported load information.

        self.assertEqual('1.2.3.4', LoadInfo.GetIdleInstanceIpAddress())
    def testGetIdleInstanceIpAddress(self):
        LoadInfo.InitializeTable()
        LoadInfo.AddInstance('test-instance1')
        LoadInfo.RegisterInstanceIpAddress('test-instance1', '1.2.3.4')
        LoadInfo.UpdateLoadInfo('test-instance1', 55)
        LoadInfo.AddInstance('test-instance2')
        LoadInfo.RegisterInstanceIpAddress('test-instance2', '5.6.7.8')
        LoadInfo.UpdateLoadInfo('test-instance2', 11)
        LoadInfo.AddInstance('test-instance3')
        LoadInfo.RegisterInstanceIpAddress('test-instance3', '9.10.11.12')
        LoadInfo.UpdateLoadInfo('test-instance3', 66)
        LoadInfo.AddInstance('test-instance4')
        LoadInfo.RegisterInstanceIpAddress('test-instance4', '13.14.15.16')
        LoadInfo.UpdateLoadInfo('test-instance4', 22)

        # IP address should be picked up from one of the 3 least loaded instances.
        self.assertIn(LoadInfo.GetIdleInstanceIpAddress(),
                      ('1.2.3.4', '5.6.7.8', '13.14.15.16'))