def execute(self, args): d = dict(vars(args)) command = d.pop("command_class") fields = d.pop("table") xml = d.pop("xml") if xml: d['response'] = 'xml' else: d['response'] = 'json' csv_fields = d.pop("csv") no_headers = d.pop("noheaders") http_method = d.pop("method") for k,v in d.items(): if v is None: del(d[k]) if http_method: retval = client.connect().connect(http_method, command.__name__, d) else: retval = client.connect().request(command.__name__, d) return retval, fields, xml, csv_fields, no_headers
def set_up(node, data): """Transfer configuration-script on instances and run it.""" user = data['username'] ip = node[1] key_file = data['ssh-key'] client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=ip, username=user, key_filename=key_file) with SCPClient(client.get_transport()) as scp: scp.put('cloud-configuration.sh', "/home/" + user) scp.put('server.py', "/home/" + user) scp.put('clopper_pb2.py', "/home/" + user) scp.put('clopper_pb2_grpc.py', "/home/" + user) scp.put(data['credentials'], "/home/" + user) logging.info("Start installation on " + node[0]) (stdin, stdout, stderr) = client.exec_command('bash ~/cloud-configuration.sh') counter = 0 while not stdout.channel.exit_status_ready(): time.sleep(1) counter += 1 if counter % 60 == 0: logging.info("Installation in progress on " + node[0]) exit_status = stdout.channel.recv_exit_status() if exit_status == 0: logging.info("Installation on " + node[0] + " completed.") else: logging.error("Installation failed on " + node[0]) client.close()
def initClient(self, first): #init client during initialization, and when retry button is clicked print('init client') try: default_addr = ('140.143.62.99', 2333) if len(sys.argv) == 1: self.client = client.connect(*default_addr) else: self.client = client.connect(sys.argv[1], int(sys.argv[2])) self.client.connectFail(self.c.socketError) self.c.socketError.connect(notConnected) self.app.processEvents() self.client.listen() except Exception as e: #set label, lock buttons if needed print('failed') print(e) if first: notConnected() self.label.setText('not connected') self.retry.show() self.app.processEvents() return #recover buttons, set labels and others print('connected') if first == False: self.recover() else: self.dfh.setAcceptDrops(True) self.dfh.setText('Drag .mp3 .wav Files Here') self.label.setText('connected') self.app.processEvents()
def connectServer(login, server): '''\ Connection to a remote server Parameters login: string server: string ''' print "Login: "******" Server: " + server client.connect(login, "127.0.1.1", 6000)
def main(): ser = serial.Serial('/dev/ttyACM0', 9600) # should send a python dictionary client.connect() while True: data = ser.readline() print(data) client.send_to_blender(data)
def connect(self): client.setIP(self.entry1.get()) client.setPath(self.filepath) try: client.setPort(int(self.entry2.get())) client.connect() client.run() self.OnButtonClick() except: self.warning()
def runTest(self): try: # login service = client.connect('*****@*****.**') # create household hid = call(self, service.create, 'Household', dict(name='my household')) # create household member hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) # create store s0id = call(self, service.create, 'RetailStore', dict(name='Store 0')) # create household store hsid = call(self, service.create, 'HouseholdStore', dict(household=hid, retail_store=s0id)) # fetch household stores fetched = call(self, service.fetch, 'HouseholdStore', []) self.assert_(1 == len(fetched), fetched) self.assert_(fetched[0][1]['household']['name'] == 'my household') self.assert_(fetched[0][1]['retail_store']['name'] == 'Store 0') finally: # clean up call(self, service.delete, 'HouseholdStore', hsid) call(self, service.delete, 'RetailStore', s0id) call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def __call__(self, **kwargs): api = [f for f in API_REFS if f['name'] == self.method_name] if not api: print '[%s] method is not suuported.' % self.method_name return options = api[0]['options'] required_opt = [opt['option'][2:] for opt in options if opt['required'] == 'true'] missing = set(required_opt) - set(kwargs.keys()) if missing: print '[%s] option is required.' % ', '.join(list(missing)) return params = dict([(k,v) for (k,v) in kwargs.items() for opt in options if opt['option'][2:] == k]) json = client.connect(host=self.command.host,api_key=self.command.api_key, secret_key=self.command.secret_key,debug=self.command.debug ).get(self.method_name,params) if json: retval = dict2obj(json[json.keys()[0]]) if retval and hasattr(retval,'list'): return retval.list else: return retval
def main(): # start local server to respond to pings and whatnot thrd = threading.Thread(target=server.loop, args=(protocol.node.handler,)) thrd.daemon = True # to ensure program exits even if thrd still runs thrd.start() while 1: # look for things the server might want to know local_changes = statistics.gather() print 'Local changes:',local_changes node_changes = watcher.gather() print 'Node changes:',node_changes # and send them to the server try: s = client.connect(MASTER_ADDR) # 1: data push request = protocol.master.push_request(local_changes, node_changes) stamp,version,do_clear_cache = protocol.master.push_response( client.ask(s, request)) print 'Data pushed to server.' if do_clear_cache: print 'Cache cleared due to server request.' statistics.cache = {} watcher.cache = {} # check if we're out of date if version>conf.VERSION: print 'Client of out date!' print 'Version %d, latest is %d.' % (conf.VERSION, version) print 'Exiting.' import sys sys.exit(1) # 2: node list request print 'Node timestamps, server:',stamp,'mine:',neighbours.stamp if stamp!=neighbours.stamp: # request update! request = protocol.master.nodes_request() stamp,nodes = protocol.master.nodes_response( client.ask(s, request)) print 'Received',len(nodes),' new nodes with stamp:',stamp neighbours.set(stamp,nodes) client.close(s) except: import traceback traceback.print_exc() print 'Failed to connect to server. Aborting communication.' # since the server didn't get our date (and is probably down!) # we really should clear our cache, to ensure the server gets a # full picture statistics.cache = {} watcher.cache = {} # then wait, to not waste resourses print 'Sleeping...' try: time.sleep(POLLING_INTERVAL) except KeyboardInterrupt: print 'Exiting.' return 0
def has_monitord(hostname): 'Check if the host has monitord runing by trying to connect and ping.' try: s = client.connect(hostname) return client.ask(s, protocol.node.ping())=='pong' except: return False
def clustercheck(): success = True clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() ClusterCount = len(clusterIndex) counter = 0 while counter < ClusterCount: try: get = client.connect(clusterIndex[counter], 10008, "1+1") if (int(get) == 2): counter += 1 else: counter += 1 success = False except Exception: counter += 1 success = False return success
def connect(component): g = component.gump if client.connect(g.component("hostname").text, int(g.component("port").text), g.component("account").text, g.component("password").text): return True else: client.messagebox("Could not connect to %s" % g.component("hostname").text) return False
def runTest(self): try: service = client.connect() sid = service.create('StoreSection', dict(name='cold cuts')) ids = [] ids.append(call(self, service.create, 'ItemDescription', dict(store_section=sid, description='bologna', is_default=True))) ids.append(call(self, service.create, 'ItemDescription', dict(store_section=sid, description='turkey', is_default=True))) ids.append(call(self, service.create, 'ItemDescription', dict(store_section=sid, description='Turkey Pastrami', is_default=True))) ids.append(call(self, service.create, 'ItemDescription', dict(store_section=sid, description='tuscan salami', is_default=True))) ids.append(call(self, service.create, 'ItemDescription', dict(store_section=sid, description='tuq', is_default=True))) turkey_meats = service.fetch('ItemDescription', [('description', 'startswith', 'tur')]) self.assert_(not isinstance(turkey_meats, ErrorFault), turkey_meats) self.assert_(len(turkey_meats) == 2, len(turkey_meats)) descriptions = [dct['description'] for id, dct in turkey_meats] self.assert_('turkey' in descriptions, descriptions) self.assert_('Turkey Pastrami' in descriptions, descriptions) finally: for id in ids: call(self, service.delete, 'ItemDescription', id) call(self, service.delete, 'StoreSection', sid)
def clustercheckUI(): success = True clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() ClusterCount = len(clusterIndex) counter = 0 while counter < ClusterCount: try: get = client.connect(clusterIndex[counter], 10008, "1+1") if(int(float(get)) == 2): print("Server " + clusterIndex[counter] + " OK") counter += 1 else: print("Server " + clusterIndex[counter] + " FAIL") counter += 1 success = False except Exception: print("Server " + clusterIndex[counter] + " FAIL (EXCEPTION IN CODE)") counter += 1 success = False print("Done!") return success
def clustercheck(): success = True clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() ClusterCount = len(clusterIndex) counter = 0 while counter < ClusterCount: try: get = client.connect(clusterIndex[counter], 10008, "1+1") if(int(get) == 2): counter += 1 else: counter += 1 success = False except Exception: counter += 1 success = False return success
def runTest(self): try: # login and create stuff service = client.connect('*****@*****.**') hid = call(self, service.create, 'Household', dict(name='my household')) hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) sid = call(self, service.create, 'RetailStore', dict(name='The Store')) hsid = call(self, service.create, 'HouseholdStore', dict(retail_store=sid)) dairy_id = call(self, service.create, 'StoreSection', dict(name='Dairy')) desc_id = call(self, service.create, 'ItemDescription', dict(description='milk', store_section=dairy_id)) # fetch recommendations and make assertions recommendations = call(self, service.fetch, 'ItemRecommendation', [('StoreSection', '=', dairy_id)]) self.assertEqual(1, len(recommendations), pformat(recommendations)) for id, rec in recommendations: self.assertEqual('milk', rec.description) self.assertEqual('Dairy', rec.store_section.name) finally: # clean up call(self, service.delete, 'ItemDescription', desc_id) call(self, service.delete, 'StoreSection', dairy_id) call(self, service.delete, 'HouseholdStore', hsid) call(self, service.delete, 'RetailStore', sid) call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def create_front(repoUrl): if repoUrl.startswith("boar://"): front = client.connect(repoUrl) front.isRemote = True else: front = Front(Repo(repoUrl)) front.isRemote = False return front
def connect(self, _): port = int(self.port.text) ip = self.ip.text username = self.username.text if not client.connect(ip, port, username, show_error): return chat_app.createChatPage() chat_app.screen_manager.current = "Chat"
def main(): s = connect() while True: for t in range(0, 80): print(f"T: {t}") c = Compositor().new_frame() c.color_test(t) s.sendall(c.as_state_event().serialize().encode()) time.sleep(0.1)
def connectchat(self, _): ip = self.ip.text port = int(self.port.text) username = self.username.text if not client.connect(ip, port, username, show_err): return kivymdMDApp.create_chatpage() kivymdMDApp.screenmanager.current = "chat"
def runTest(self): try: # login as test1 and create a household service = client.connect('*****@*****.**') hid = call(self, service.create, 'Household', dict(name='test1 household')) hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) # login as test2 and fetch household service2 = client.connect('*****@*****.**') fetched = call(self, service2.fetch, 'HouseholdMember', []) # assert that the fetched list is empty self.assertEqual(0, len(fetched), pformat(fetched)) finally: # clean up call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def connect(component): g = component.gump if client.connect( g.component("hostname").text, int(g.component("port").text), g.component("account").text, g.component("password").text): return True else: client.messagebox("Could not connect to %s" % g.component("hostname").text) return False
def connect(self, _): port = int(self.port.text) ip = self.ip.text username = self.username.text # Connect and handle errors if can't connect if not client.connect(ip, port, username, show_error): return chat_app.create_chat_page() chat_app.screen_manager.current = "Chat"
def runTest(self): ids = [] try: service = client.connect() for name in "barfooquux", "FoOquux", "bar": ids.append(call(self, service.create, "RetailStore", {"name": name})) pairs = call(self, service.fetch, "RetailStore", [("name", "like", "foo")]) self.assertEqual(ids[:2], [id for id, _ in pairs]) finally: for id in ids: call(self, service.delete, "RetailStore", id)
def __init__(self, mode): self.mode = mode # start connection if mode == "client": self.sock = connect() if mode == "server": self.sock = serve() #initise class wide variables self.packets = {} self._queue = [] self.temp_id = 0
def main(): """ Connect to an SNI-enabled server and request a specific hostname, specified by argv[1], of it. """ if len(argv) < 2: print 'Usage: %s <hostname>' % (argv[0],) return 1 client = socket() print 'Connecting...', stdout.flush() client.connect(('127.0.0.1', 8443)) print 'connected', client.getpeername() client_ssl = Connection(Context(TLSv1_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name(argv[1]) client_ssl.do_handshake() print 'Server subject is', client_ssl.get_peer_certificate().get_subject() client_ssl.close()
def main(): """ Connect to an SNI-enabled server and request a specific hostname, specified by argv[1], of it. """ if len(argv) < 2: print 'Usage: %s <hostname>' % (argv[0], ) return 1 client = socket() print 'Connecting...', stdout.flush() client.connect(('127.0.0.1', 8443)) print 'connected', client.getpeername() client_ssl = Connection(Context(TLSv1_METHOD), client) client_ssl.set_connect_state() client_ssl.set_tlsext_host_name(argv[1]) client_ssl.do_handshake() print 'Server subject is', client_ssl.get_peer_certificate().get_subject() client_ssl.close()
def test_simple_push_pull(self): queue = random_queue_name() with client.connect(*self.server_addr) as c: c.ping() c.push("my-task", queue=queue) task = c.fetch(timeout=1, queues=[queue]) assert task["name"] == "my-task" c.nack(task["id"]) task = c.fetch(timeout="1.2s", queues=[queue]) assert task["name"] == "my-task" c.ack(task["id"])
def connect(self, _): # Get information for sockets client port = int(self.port.text) ip = self.ip.text username = self.username.text if not client.connect(ip, port, username, show_error): return # Create chat page and activate it chat_app.create_chat_page() chat_app.screen_manager.current = 'Chat'
def distribute_test_suite(node_dict, test_suite, data): """SSH into the remote instance and transfer data with SCP.""" # compress project-dir project = shutil.make_archive(expanduser('~/tmp/project'), 'gztar', root_dir=data['project']) writer = Writer(data, test_suite.content) #distribute test suite among instances for node, bundle in zip(node_dict.iteritems(), test_suite): config, cl = writer.generate_input(bundle) ip = node[1] key_file = data['ssh-key'] user = data['username'] client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=ip, username=user, key_filename=key_file) with SCPClient(client.get_transport()) as scp: scp.put(config, "/home/" + user + "/tmp/config.tar.gz") scp.put(cl, "/home/" + user + "/tmp/params.tar.gz") scp.put(project, "/home/" + user + "/tmp/project.tar.gz") client.close()
def send_data(self): global server_answer, chat, chance if self.user_type.get(): user_data = {"operation": "login", "user": self.user_name.get(), "password": hashlib.md5(self.password.get()).hexdigest(), 'type': 'normal'} else: user_data = {"operation": "login", "user": self.user_name.get(), "password": None, 'type': 'guest'} server_answer = client.connect(user_data) if not server_answer: root.destroy() else: self.lf.pack_forget() chat = ChatOpen(server_answer)
def optin(update, context, recipient, sk): """ Checks if user already optin for an ASA, subscribes users if condition is false. :param update: :param context: :param recipient: public key of subscriber :param sk: Signature of subscriber :return: true if success. """ algod_client = connect(update, context) params = algod_client.suggested_params() # Check if recipient holding DMT2 asset prior to opt-in print(algod_client.account_info(recipient)) account_info_pk = algod_client.account_info(recipient) print(account_info_pk) holding = None # idx = 0 for assetinfo in account_info_pk['assets']: scrutinized_asset = assetinfo['asset-id'] # idx = idx + 1 if asset_id == scrutinized_asset: holding = True msg = "This address has opted in for DMT2, ID {}".format(asset_id) logging.info("Message: {}".format(msg)) logging.captureWarnings(True) break if not holding: # Use the AssetTransferTxn class to transfer assets and opt-in txn = AssetTransferTxn(sender=recipient, sp=params, receiver=recipient, amt=0, index=asset_id) # Sign the transaction # Firstly, convert mnemonics to private key. # For tutorial purpose, we will focus on using private key # sk = mnemonic.to_private_key(seed) sendTrxn = txn.sign(sk) # Submit transaction to the network txid = algod_client.send_transaction(sendTrxn) message = "Transaction was signed with: {}.".format(txid) wait = wait_for_confirmation(update, context, algod_client, txid) time.sleep(2) hasOptedIn = bool(wait is not None) if hasOptedIn: update.message.reply_text(f"Opt in success\n{message}") return hasOptedIn
def test_transaction(self): queue = random_queue_name() with client.connect(*self.server_addr) as c: c.ping() c.push("my-task", queue=queue) task = c.fetch(timeout=1, queues=[queue]) assert task["name"] == "my-task" with c.transaction() as tx: tx.ack(task["id"]) for _ in range(10): tx.push("another-task", queue=queue)
def connectionTest(): # Init and reset database connection _, cursor = connect() # Run query cursor.execute("SELECT * from patients limit 10;") data = cursor.fetchall() print(data) # Close connection closeConnection() # return data return json.dumps(data, indent=4, sort_keys=True, default=str)
def run(self): midi_input, _port_name = open_midiinput(port="aurora") midi_input.set_callback(self.callback) self.led_index = 0 self.key = 0 self.km = KeyMapper() self.m = dict(self.km.km) self.compositor = Compositor() self.s = connect() while True: time.sleep(0.05) frame = self.compositor.new_frame() wire_event = frame.as_state_event() payload = wire_event.serialize().encode() self.s.sendall(payload)
def test_transaction_failure(self): queue = random_queue_name() with client.connect(*self.server_addr) as c: # Transaction commit must fail. Any operation within the transaction must be buffered. with self.assertRaises(client.ResponseError): with c.transaction() as tx: try: tx.push("a-task", queue=queue) tx.ack(1234567890) except Exception as exc: raise Exception("this must not fail") from exc # Failed transaction must not execute any operation. with self.assertRaises(client.EmptyError): c.fetch(queues=[queue], timeout="1ms")
def runTest(self): try: # create stuff service = client.connect('*****@*****.**') hid = call(self, service.create, 'Household', dict(name='my household')) hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) # fetch and make assertions results = call(self, service.fetch, 'HouseholdMember', []) self.assertEqual(1, len(results)) finally: # clean up call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def test_server_down(self): queue = random_queue_name() with client.connect(*self.server_addr) as c: c.ping() # Stopping the server must disconnect the client. self._server_process.terminate() self._server_process.wait() for _ in range(30): time.sleep(0.3) if not c.is_connected(): return raise Exception("client still connected")
def runTest(self): try: service = client.connect('*****@*****.**') hid = service.create('Household', dict(name='my-household')) self.make_assertion(hid) hmid = service.create('HouseholdMember', dict(household=hid)) self.make_assertion(hmid) hms = service.fetch('HouseholdMember') self.make_assertion(hms) finally: d_hm = service.delete('HouseholdMember', hmid) try: self.assert_(not isinstance(d_hm, ErrorFault), d_hm) finally: d_h = service.delete('Household', hid) self.assert_(not isinstance(d_h, ErrorFault), d_h)
def __init__(self): # Get a username before launching the main chat application username_popup = tkinter.Tk() username_popup.withdraw() self.username = simpledialog.askstring("Username", "Please enter a username", parent=username_popup) # Connect to the server and assign the username entered above if not client.connect(IP, PORT, self.username, show_error): return # Start the GUI Thread(target=self.loop).start() # Start listening for messages from the server client.start_listening(self.receive_message, show_error)
def runTest(self): try: # login service = client.connect('*****@*****.**') # create household hid = call(self, service.create, 'Household', dict(name='my household')) # create household member hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) # create store s0id = call(self, service.create, 'RetailStore', dict(name='Store 0')) s1id = call(self, service.create, 'RetailStore', dict(name='Store 1')) # create lists for both stores l0id = call(self, service.create, 'ShoppingList', dict(RetailStore=s0id)) l1id = call(self, service.create, 'ShoppingList', dict(RetailStore=s1id)) # fetch those lists lists = call(self, service.fetch, 'ShoppingList') self.assertEqual(2, len(lists), lists) def make_assertions(expected_id, expected_name): for id, shop_list in lists: if id == expected_id: self.assertEqual(shop_list.household_store.retail_store.name, expected_name, shop_list) break else: self.fail('Did not find id=%s in lists' % expected_id) make_assertions(l0id, 'Store 0') make_assertions(l1id, 'Store 1') finally: # clean up call(self, service.delete, 'ShoppingList', l1id) call(self, service.delete, 'ShoppingList', l0id) call(self, service.delete, 'RetailStore', s1id) call(self, service.delete, 'RetailStore', s0id) call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def get_name(self): global currentServer name, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:') if ok: if name == '': self.get_name() else: self.name = name self.sock = connect(self.name, currentServer) thread = Thread(target=self.handle_chat) thread.start() else: box = QMessageBox() box.setText('Ухади') box.exec() app.closeAllWindows() stop()
def execute(clusterComputer, command, highValue): clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() clusterLenght = len(clusterIndex) get = "" if(clusterComputer > clusterLenght): get = "ERROR!" elif highValue == 1: get = highValueClient.connect(clusterIndex[(clusterComputer - 1)], 10008, command) else: get = client.connect(clusterIndex[(clusterComputer - 1)], 10008, command) return get
def enter_game(self, tokdef=''): self.token_code = tokdef if (self.token_code != ''): Global.data = client.connect(self.get_token()) Global.token = self.get_token() if (Global.data == 'invalid token'): layout = GridLayout(cols=1, padding=15, spacing=15) label__text = Label(text='Invalid Token.\nTry Again') layout.add_widget(label__text) popup = Popup(title='Error', content=layout, size_hint=(None, None), size=(200, 100)) popup.open() else: Playground_Screen = PlaygroundScreen(name='playground') sm.add_widget(Playground_Screen) sm.current = 'playground'
def main(): s = connect() print(f"Connected. Starting handlers.") eh = EventHandler(s) midi_input, _port_name = open_midiinput(port="aurora") midi_input.set_callback(eh.on_midi_event) print(midi_input) try: while True: time.sleep(0.05) eh.on_parsed_event(mido.Message("clock")) except KeyboardInterrupt: pass finally: midi_input.close_port() del midi_input
def main(): cl = client.connect(("", DEFAULT_MASTER_CLIENT_PORT)) f = cl.create("hello.txt") for i in range(10): f.write(b"Hello") f.close() f = cl.open("hello.txt") while True: buf = f.read(len("Hello")) if not buf: break print(buf) f.close() cl.delete("hello.txt") cl.close()
def execute(clusterComputer, command, highValue): clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() clusterLenght = len(clusterIndex) get = "" if (clusterComputer > clusterLenght): get = "ERROR!" elif highValue == 1: get = highValueClient.connect(clusterIndex[(clusterComputer - 1)], 10008, command) else: get = client.connect(clusterIndex[(clusterComputer - 1)], 10008, command) return get
def runTest(self): try: service = client.connect() a_id = call(self, service.create, 'StoreSection', dict(name='sect A')) b_id = call(self, service.create, 'StoreSection', dict(name='sect B')) c_id = call(self, service.create, 'StoreSection', dict(name='sect C')) # passing the empty list of filters is very important, otherwise the # filters argument might be changed by the other tests (?!?!?!?!?!?!) # and this call will return an empty list as the result sects = call(self, service.fetch, 'StoreSection', []) self.assert_(len(sects) == 3, len(sects)) sects = dict(sects) self.assert_(sects[a_id]['name'] == 'sect A', sects[a_id]['name']) self.assert_(sects[b_id]['name'] == 'sect B', sects[b_id]['name']) self.assert_(sects[c_id]['name'] == 'sect C', sects[c_id]['name']) finally: call(self, service.delete, 'StoreSection', c_id) call(self, service.delete, 'StoreSection', b_id) call(self, service.delete, 'StoreSection', a_id)
def runTest(self): try: service = client.connect() #print 'Connecting to %s' % service id = service.create('RetailStore', dict(name='foo')) #print 'id=%s (%s)' % (id, type(id)) self.assert_(isinstance(id, (int, long)), 'id=%s (%s)' % (id, type(id))) error = service.create('RetailStore', dict(name='foo')) #print error self.assert_(isinstance(error, ErrorFault), error) fetched = service.fetch('RetailStore', [('name', '=', 'foo')], 1) if isinstance(fetched, ErrorFault): self.fail(fetched) fetched_id, fetched_store = fetched self.assertEqual(id, fetched_id, fetched_id) self.assertEqual('foo', fetched_store['name']) service.update('RetailStore', id, dict(name='bar')) self.assertEqual('bar', service.get('RetailStore', id)['name']) finally: service.delete('RetailStore', id) self._make_assertions(None, service.get('RetailStore', id))
def main(args): from sys import exit from optparse import OptionParser import logging import time import client js_logger = logging.getLogger("") filename = "robot-output.{0}".format(time.strftime("%H%M%S")) rec_file = "recs/" + filename + ".rec" log_file = "logs/" + filename + ".log" logging.basicConfig(filename=log_file, filemode="w",level=logging.DEBUG,format="%(module)s:%(levelname)s: %(message)s") js_logger.addHandler(client.logconsole) parser = OptionParser() parser.add_option("-a", "--addr", default = "localhost:8880") parser.add_option("-s", "--seat", type="int", default = 1) parser.add_option("-g", "--game", default = None) parser.add_option("-n", "--nick", default = None) parser.add_option("-w", "--wait", action="store_true", default = False) parser.add_option("-r", "--recordfile", default = rec_file) parser.add_option("-p", "--play", action="store_true", default = False) (options, args) = parser.parse_args() print options if ":" not in options.addr: print "try using host:port" sys.exit(-1) host, port = options.addr.split(":") client = VCRClient(options.recordfile, not options.play) if not client.connect((host, int(port))): print("Could not connect to: {0}".format(options.addr)) exit(-1) client.setup(options.game, not options.wait, options.seat, options.nick) client.run()
def runTest(self): try: # create stuff service = client.connect('*****@*****.**') hid = call(self, service.create, 'Household', dict(name='my household')) hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) s0id = call(self, service.create, 'RetailStore', dict(name='Store 0')) s1id = call(self, service.create, 'RetailStore', dict(name='Store 1')) hsid = call(self, service.create, 'HouseholdStore', dict(household=hid, retail_store=s0id)) l0id = call(self, service.create, 'ShoppingList', dict(RetailStore=s0id)) l1id = call(self, service.create, 'ShoppingList', dict(RetailStore=s1id)) # fetch the list using HouseholdStore - should return l0, but not l1 lists = call(self, service.fetch, 'ShoppingList', [('HouseholdStore', '=', hsid)]) self.assertEqual(1, len(lists), pformat(lists)) def make_assertions(expected_id, expected_name): for id, shop_list in lists: if id == expected_id: self.assertEqual(shop_list.household_store.retail_store.name, expected_name, shop_list) break else: self.fail('Did not find id=%s in lists' % expected_id) make_assertions(l0id, 'Store 0') finally: # clean up call(self, service.delete, 'ShoppingList', l1id) call(self, service.delete, 'ShoppingList', l0id) call(self, service.delete, 'HouseholdStore', hsid) call(self, service.delete, 'RetailStore', s1id) call(self, service.delete, 'RetailStore', s0id) call(self, service.delete, 'HouseholdMember', hmid) call(self, service.delete, 'Household', hid)
def runTest(self): ids = [] service = client.connect() try: ids.append( call(self, service.create, "RetailStore", {"name": "st0"})) st0 = call(self, service.get, "RetailStore", ids[0]) error = service.clone(st0["_key"], {"name": "st0"}) self.assert_(isinstance(error, ErrorFault), error) ids.append( call(self, service.clone, st0["_key"], {"name": "st1"})) finally: for id in ids: call(self, service.delete, "RetailStore", id)
def run(batch_size: int): with client.connect("localhost", 12345) as c: queue_name = random.choice([ "default", "highprio", "lowprio", "email", "sysalert", "bacground", "service.bob", "service.alice", "service.charlie", "service.danny", "invoices", "monitoring", ]) to_ack: List[int] = [] while True: c.ping() start = time.time() with c.transaction() as tx: payload = { "something_id": 1241244, "client_id": 104922, "user_id": 91492, "recover": True, "text": "In publishing and graphic design, Lorem ipsum is a placeholder text" "commonly used to demonstrate the visual form of a document or a typeface without" "relying on meaningful content", "now": start, } for _ in range(batch_size): tx.push("my-task", payload, queue=queue_name) for id in to_ack: tx.ack(id) to_ack = [] for _ in range(254 // 2): try: task = c.fetch(timeout=1, queues=[queue_name]) to_ack.append(task["id"]) except client.EmptyError: break work_time_ms = int((time.time() - start) * 1000)
def runTest(self): hid = hmid = rsid = None try: service = client.connect('*****@*****.**') hid = call(self, service.create, 'Household', dict(name='foo household')) hmid = call(self, service.create, 'HouseholdMember', dict(household=hid)) rsid = call(self, service.create, 'RetailStore', dict(name='Big Box')) # create ShoppingList by passing in RetailStore slid = hsid = None try: slid = call(self, service.create, "ShoppingList", dict(RetailStore=rsid)) # creating a ShoppingList in this manner in turn creates a # HouseholdStore behind the scenes hsid, _ = call(self, service.fetch, 'HouseholdStore', [("retail_store", "=", rsid)], 1) self.assert_(hsid is not None, str(hsid)) finally: if slid: call(self, service.delete, "ShoppingList", slid) if hsid: call(self, service.delete, "HouseholdStore", hsid) # create ShoppingList by passing in HouseholdStore hsid2 = slid2 = None try: hsid2 = call(self, service.create, 'HouseholdStore', dict(retail_store=rsid)) slid2 = call(self, service.create, "ShoppingList", dict(HouseholdStore=hsid2)) finally: if slid2: call(self, service.delete, "ShoppingList", slid2) if hsid2: call(self, service.delete, 'HouseholdStore', hsid2) finally: if rsid: call(self, service.delete, 'RetailStore', rsid) if hmid: call(self, service.delete, 'HouseholdMember', hmid) if hid: call(self, service.delete, 'Household', hid)
def clustercheckUI(): success = True clusterIndexRaw = FileOperations.readFile("clusterIndex.cli") clusterIndex = clusterIndexRaw.split() ClusterCount = len(clusterIndex) counter = 0 while counter < ClusterCount: try: get = client.connect(clusterIndex[counter], 10008, "1+1") if (int(float(get)) == 2): print("Server " + clusterIndex[counter] + " OK") counter += 1 else: print("Server " + clusterIndex[counter] + " FAIL") counter += 1 success = False except Exception: print("Server " + clusterIndex[counter] + " FAIL (EXCEPTION IN CODE)") counter += 1 success = False print("Done!") return success
def play_tictactoe(host, port): sock = connect(host, port, 'tictactoe') return play(sock, get_move)
#!/usr/bin/env python import client if __name__=='__main__': client.connect() print client.close()