def test_should_convert_header_values_to_basestring(self): # given client = Server('http://localhost:{0}'.format(self.port), verbose=1, headers={'X-Test' : 123}) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue('x-test' in headers) self.assertEqual(headers['x-test'], '123')
def test_should_add_additional_headers(self): # given client = Server('http://localhost:{0}'.format(self.port), verbose=1, headers={'X-My-Header' : 'Test'}) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue('x-my-header' in headers) self.assertEqual(headers['x-my-header'], 'Test')
def test_should_not_override_content_length(self): # given client = Server('http://localhost:{0}'.format(self.port), verbose=1, headers={'Content-Length' : 'invalid value'}) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue('content-length' in headers) self.assertNotEqual(headers['content-length'], 'invalid value')
def test_should_extract_headers(self): # given client = Server('http://localhost:{0}'.format(self.port), verbose=1) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue(len(headers) > 0) self.assertTrue('content-type' in headers) self.assertEqual(headers['content-type'], 'application/json-rpc')
def test_should_override_headers(self): # given client = Server('http://localhost:{0}'.format(self.port), verbose=1, headers={ 'User-Agent' : 'jsonrpclib test', 'Host' : 'example.com' }) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertEqual(headers['user-agent'], 'jsonrpclib test') self.assertEqual(headers['host'], 'example.com')
token = { 'timestamp': int(time.mktime(time.gmtime())), 'accesslevel': accessLevel } data = json.dumps(token) iv = os.urandom(AES.block_size) cipher = AES.new(RPC_SERVER_SECRET, mode=AES.MODE_CBC, IV=iv) data += '\x00' * (16 - (len(data) % AES.block_size)) token = cipher.encrypt(data) return base64.b64encode(iv + token) random.seed() while True: try: res = client.ping(generate_token(700), 12345) if res != 12345: print "Is the server accessable?\n" exit # How many times a day is this script going to be called? ChecksPerDay = 60.0 * 24.0 # Once a minute InvasionsPerDay = 72.0 # How many invasions a day per district BaseInvasionChance = InvasionsPerDay / ChecksPerDay safeHarbor = {'Wacky Woods'} superDistricts = {'Roaring Rivers'} while True: shards = client.listShards(generate_token(700)) print shards
def generate_token(accessLevel): """ Generate an RPC server token with the given access level. """ token = {'timestamp': int(time.mktime(time.gmtime())), 'accesslevel': accessLevel} data = json.dumps(token) iv = os.urandom(AES.block_size) cipher = AES.new(RPC_SERVER_SECRET, mode=AES.MODE_CBC, IV=iv) data += '\x00' * (16 - (len(data)%AES.block_size)) token = cipher.encrypt(data) return base64.b64encode(iv + token) random.seed() while True: try: res = client.ping(generate_token(700), 12345) if res != 12345: print "Is the server accessable?\n" exit # How many times a day is this script going to be called? ChecksPerDay = 60.0*24.0 # Once a minute InvasionsPerDay = 72.0 # How many invasions a day per district BaseInvasionChance = InvasionsPerDay/ChecksPerDay safeHarbor = {'Wacky Falls'} superDistricts = {'Nuttyboro'} while True: shards = client.listShards(generate_token(700))
class Client(object): def __init__(self, host, port): super(Client, self).__init__() self.log = logging.getLogger(self.__class__.__name__) self.log.addHandler(logging.StreamHandler()) self.log.setLevel(logging.INFO) self.url = "http://%s:%s" % (host, port) self.log.info("Connecting to %s" % self.url) self._server = Server(self.url) try: self._server.ping() except: raise EnvironmentError("Server unavailable") self._pdict = {} self.message = "" self.monitor = Monitoring(host) self.monitor.start() def commit(self, path, message): """ Commit before running :param path: path to svn repository :param message: a commit message :return: """ curdir = os.getcwd() self.message = message os.chdir(path) subprocess.check_call(["svn", "up"]) subprocess.check_call(["svn", "commit", "-m", message]) os.chdir(curdir) def set_parameters(self, pdict): """ Run parameters :param pdict: :return: """ self._pdict = pdict def execute(self, cleanup=True): """ Execute the bugger :return: """ res = None try: res = self._server.execute(self._pdict, cleanup) except KeyboardInterrupt: self.monitor.stop() server2 = Server(self.url) server2.kill() except socket.error: self.log.error("Server was interrupted") exit(1) finally: self.monitor.stop() if res is None: raise ValueError("Run failed") resstr = "%s\t%s\t %s\t %s\t %s\t %s\t %s" % ( str(datetime.datetime.utcnow()), self.message, self._pdict["cpuRangeVal"], self._pdict["outputDir"], res["Wallclock"], res["peak"] / 1024.**3, res["avg"] / 1024**3) self.log.info( "date \t\t\t message \t\t cpu \t outputdir \t time \t peak_mem \t avg_mem" ) self.log.info(resstr) with open(os.path.expanduser("~/result.dat"), "a") as out: out.write(resstr + "\n")
class Client(object): def __init__(self, host, port): super(Client, self).__init__() self.log = logging.getLogger(self.__class__.__name__) self.log.addHandler(logging.StreamHandler()) self.log.setLevel(logging.INFO) self.url = "http://%s:%s" % (host, port) self.log.info("Connecting to %s" % self.url) self._server = Server(self.url) try: self._server.ping() except: raise EnvironmentError("Server unavailable") self._pdict = {} self.message = "" self.monitor = Monitoring(host) self.monitor.start() def commit(self, path, message): """ Commit before running :param path: path to svn repository :param message: a commit message :return: """ curdir = os.getcwd() self.message = message os.chdir(path) subprocess.check_call(["svn", "up"]) subprocess.check_call(["svn", "commit", "-m", message]) os.chdir(curdir) def set_parameters(self, pdict): """ Run parameters :param pdict: :return: """ self._pdict = pdict def execute(self, cleanup=True): """ Execute the bugger :return: """ res = None try: res = self._server.execute(self._pdict, cleanup) except KeyboardInterrupt: self.monitor.stop() server2 = Server(self.url) server2.kill() except socket.error: self.log.error("Server was interrupted") exit(1) finally: self.monitor.stop() if res is None: raise ValueError("Run failed") resstr = "%s\t%s\t %s\t %s\t %s\t %s\t %s" % (str(datetime.datetime.utcnow()), self.message, self._pdict["cpuRangeVal"], self._pdict["outputDir"], res["Wallclock"], res["peak"]/1024.**3, res["avg"]/1024**3) self.log.info("date \t\t\t message \t\t cpu \t outputdir \t time \t peak_mem \t avg_mem") self.log.info(resstr) with open(os.path.expanduser("~/result.dat"), "a") as out: out.write(resstr+"\n")