def assert_no_requests_in_progress_state(client: utils.Client, requests_amount, submitted_requests): """Check get_all request returns expected in_progress values.""" query_params = { "per_page": requests_amount, "page": 1, "state": "in_progress" } response = client.fetch_all_requests(query_params, all_pages=False) assert response.status == 200 assert all(item["state"] == "in_progress" for item in response.data["items"] ), "At least one of requests was not in in_progress state" response_ids = set(item["id"] for item in response.data["items"]) # Check there are no completed requests in the response. assert not any( request_id in response_ids for request_id in submitted_requests ), ( f"At least one of requests {response_ids} was in completed state. ", "All requests are expected to be in other state than completed.", ) assert 0 <= len(response.data["items"]) <= requests_amount, ( f"Number of obtained responses ({len(response.data['items'])}) " f"is not in the range from 0 to {requests_amount}")
def __init__(self, login, password, key, server_name): self.login = login self.password = password self.key = key self.client = Client(server_name) self.token = None self.connected = False
def setUp(self) -> None: self.client_a = Client() self.client_b = Client() self.client_c = Client() self.client_a.connect() self.client_b.connect() self.client_c.connect()
def __init__(self, port, parent=None): QWidget.__init__(self, parent=parent) self.port = port self.sharedMemory = {} memFilePath = '{}.mem'.format(port) if os.path.isfile(memFilePath): try: with open(memFilePath) as f: self.sharedMemory = pickle.load(f) sys.stdout.write(u"[INFO] Wczytano zapisaną pamięć.\n", name=port) except: sys.stdout.write(u"[BŁĄD] Błąd odczytywania pamięci. Resetuję!\n", name=port) #self.sharedMemory = SharedDict(self.sharedMemory) try: self.client = Client(port) except: #print "Brak połączenia z serwerem!" #self.client = None raise NoServerConnection() self.workerThread = None self.uiUpdateEvent = threading.Event() self.snippetQueue = [] self.context = {} self.context['mem'] = self.sharedMemory self.context['active'] = None self.context['client'] = self.client # TODO: polaczenie z klientem self.timer = QTimer() self.timer.setInterval(0) self.timer.timeout.connect(self.tick) self.timer.start() self.actions = [] self.setupUI() # Autoload modules #for modulePath in filter(lambda x: x[-3:]=='.py', os.listdir('..')): for modulePath in [ x for x in os.listdir('..') if x[-3:] == '.py' ]: self.strategies.load(os.path.join("..", modulePath))
def assert_completed_requests(client: utils.Client, submitted_ids): """Check get_all request returns submitted requests in complete state.""" query_params = { "per_page": len(submitted_ids), "page": 1, "state": "complete" } submitted_ids = submitted_ids.copy() while len(submitted_ids): response = client.fetch_all_requests(query_params, all_pages=False) assert response.status == 200 assert response.data["items"], "Cachito did not return any requests" for response_item in response.data["items"]: assert response_item["state"] == "complete" if response_item["id"] in submitted_ids: submitted_ids.remove(response_item["id"]) query_params["page"] += 1 assert len(submitted_ids) == 0
class TestProtocolRandomStrings(TestCase): def setUp(self) -> None: self.client = Client() self.client.connect() def tearDown(self) -> None: self.client.disconnect() def test_echo_5_byte_string(self) -> None: for string in generate_random_string(num_strings=5, len_strings=5): with self.subTest(): self.assertEqual(string, self.client.send(string)) def test_echo_10_byte_string(self) -> None: for string in generate_random_string(num_strings=5, len_strings=10): with self.subTest(): self.assertEqual(string, self.client.send(string)) def test_echo_15_byte_string(self) -> None: for string in generate_random_string(num_strings=5, len_strings=15): with self.subTest(): self.assertEqual(string, self.client.send(string))
def setUp(self) -> None: self.client = Client() self.client.connect()
from utils import Client if __name__ == '__main__': username = input('Enter your username: ') client = Client(username) client.connect()
def main(): HOST = '127.0.0.1' PORT = 9090 client = Client(HOST, PORT)
class Environment(QWidget): def __init__(self, port, parent=None): QWidget.__init__(self, parent=parent) self.port = port self.sharedMemory = {} memFilePath = '{}.mem'.format(port) if os.path.isfile(memFilePath): try: with open(memFilePath) as f: self.sharedMemory = pickle.load(f) sys.stdout.write(u"[INFO] Wczytano zapisaną pamięć.\n", name=port) except: sys.stdout.write(u"[BŁĄD] Błąd odczytywania pamięci. Resetuję!\n", name=port) #self.sharedMemory = SharedDict(self.sharedMemory) try: self.client = Client(port) except: #print "Brak połączenia z serwerem!" #self.client = None raise NoServerConnection() self.workerThread = None self.uiUpdateEvent = threading.Event() self.snippetQueue = [] self.context = {} self.context['mem'] = self.sharedMemory self.context['active'] = None self.context['client'] = self.client # TODO: polaczenie z klientem self.timer = QTimer() self.timer.setInterval(0) self.timer.timeout.connect(self.tick) self.timer.start() self.actions = [] self.setupUI() # Autoload modules #for modulePath in filter(lambda x: x[-3:]=='.py', os.listdir('..')): for modulePath in [ x for x in os.listdir('..') if x[-3:] == '.py' ]: self.strategies.load(os.path.join("..", modulePath)) def setupUI(self): self.setWindowTitle("%d" % self.port) self.mdi = QMdiArea() self.mdi.setHorizontalScrollBarPolicy( Qt.ScrollBarAsNeeded ) self.mdi.setVerticalScrollBarPolicy( Qt.ScrollBarAsNeeded ) self.inter = Interpreter(self.context) self.mdi.addSubWindow(self.inter, Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowMaximized) #self.mdi.addSubWindow(FileBrowser()) # Dock windows self.strategies = Strategies() #stratDock = QDockWidget("Strategies", self) #stratDock.setWidget(self.strategies) #self.addDockWidget(Qt.RightDockWidgetArea, stratDock) # Actions newDocIcon = QIcon(QPixmap("img/newdoc.png")) playIcon = QIcon(QPixmap("img/Play.png")) newSnippetAction = QAction(newDocIcon, "Nowy skrawek", self) newSnippetAction.setShortcut('F1') self.actions.append(newSnippetAction) runSnippetAction = QAction(playIcon, "Uruchom skrawek", self) runSnippetAction.setShortcut('F9') self.actions.append(runSnippetAction) layout = QHBoxLayout() layout.addWidget(self.mdi) layout.addWidget(self.strategies) self.setLayout(layout) # Connecting QWidget.connect(self.strategies, SIGNAL('strategyChanged'), self.strategyChanged) QWidget.connect(newSnippetAction, SIGNAL('triggered()'), self.newSnippet) QWidget.connect(runSnippetAction, SIGNAL('triggered()'), self.runSnippet) def strategyChanged(self, old, new): if old != None: with output(self.port, True): old.remove() self.workerThread.work = False self.workerThread.join() # wait for QThread self.workerThread = None if hasattr(old, '__widget__'): self.mdi.removeSubWindow(old.__widget__.parent()) self.tick() self.context['active'] = new if new: with output(self.port): print "Starting new worker..." widget = QWidget() widget.setWindowTitle(new.name()) self.mdi.addSubWindow(widget, Qt.WindowTitleHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowMaximized) new.__widget__ = widget new.mem = self.sharedMemory new.widget = widget new.client = self.client try: with output(self.port): new.install() except: traceback.print_exc() widget.parent().adjustSize() self.workerThread = WorkerThread(self.client, new, self.uiUpdateEvent) self.workerThread.daemon = True self.workerThread.start() # czyta stdout dla danego interpretera i robi update GUI def tick(self): if self.context['active'] and self.uiUpdateEvent.isSet(): self.uiUpdateEvent.clear() with output(self.port, True): self.context['active'].updateUI() data = sys.stdout.getOutput(self.port) if data: count = len( self.inter.out.toPlainText().split('\n') ) - 100 if count > 0: cursor = self.inter.out.textCursor() cursor.movePosition( QTextCursor.Start ) cursor.movePosition( QTextCursor.Down, QTextCursor.KeepAnchor, count) cursor.removeSelectedText() self.inter.write(data) def newSnippet(self): w = SnippetEditor() QWidget.connect(w, SIGNAL('codeOutput'), self.inter.write) self.mdi.addSubWindow(w) w.show() def runSnippet(self): w = self.mdi.activeSubWindow().widget() if hasattr(w, 'runCode') and callable(w.runCode): w.runCode(self.context) def queueSnippet(self): w = self.mdi.activeSubWindow().widget() if hasattr(w, 'runCode') and callable(w.runCode): self.workerThread.snippetQueue.append( (w, self.context) ) def renameSnippet(self, title): #print self.mdi.activeSubWindow().widget() if self.mdi.activeSubWindow(): self.mdi.activeSubWindow().setWindowTitle(title) #if hasattr(w, 'runCode') and callable(w.runCode): def cleanup(self): self.client.close() if self.workerThread is not None: self.workerThread.work = False
import json from flask import Flask, request from flask.templating import render_template from flask.wrappers import Response from utils import Client HASURA_URL = "https://unbiased-rabbit-96.hasura.app/v1/graphql" HASURA_HEADERS = { "X-Hasura-Admin-Secret": "5qEITb9AYwnOvLvxobVquKwStq7DK3fualHam6xEZ46zm03R433EIuzqbKwinXGJ" } client = Client(url=HASURA_URL, headers=HASURA_HEADERS) app = Flask(__name__) @app.route('/api/keywords', methods=['GET']) def keywords(): keywords_response = client.get_keywords() data = keywords_response.get('data').get('keyword') keywords_list = list() if data: for keyword in data: keywords_list.append(keyword['keyword_value']) keywords_list = list(set(keywords_list))
class MemberAPI (object): def __init__(self, login, password, key, server_name): self.login = login self.password = password self.key = key self.client = Client(server_name) self.token = None self.connected = False def get(self, action, *values): if self.token is None: raise NotConnected() return self.client.get(action, self.token, *values) def post(self, data): path = '/apimember/services/MemberService?wsdl' return self.client.post(path, data) def __enter__(self): self.__connect() return self def __exit__(self, exc_type, exc_val, exc_tb): # FIXME: manage exceptions if self.connected: self.__disconnect() def __connect(self): response = self.client.get('/apimember/services/rest/connect/open/', self.login, self.password, self.key) self.token = response.find('result').text def __disconnect(self): if self.token is None: raise NotConnected() self.client.get('/apimember/services/rest/connect/close/', self.token) self.token = None def insert_member_by_email(self, email): """returns a job id""" response = self.get('/apimember/services/rest/member/insert/', email) return response.result def insert_or_update_member_by_object(self, email, values): """returns a job id""" # email is the object key, so it cannot be empty if not email: raise ValueError("insert_or_update_member_by_object: email cannot be empty") data = u"""<?xml version="1.0" encoding="latin1" standalone="yes"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.service.apimember.emailvision.com/"> <soapenv:Header/> <soapenv:Body> <api:insertOrUpdateMemberByObj> <token>%s</token> <member> <dynContent> """ % self.token for key in values: data += u"""<entry><key>%s</key><value>%s</value></entry>""" % (key, values[key]) data += u"""</dynContent> <memberUID>email:%s</memberUID> </member> </api:insertOrUpdateMemberByObj> </soapenv:Body> </soapenv:Envelope> """ % email response = self.post(data) r = response.soap_find('Body') r = r.find('{http://api.service.apimember.emailvision.com/}insertOrUpdateMemberByObjResponse') r = r.find('return').text return r def update_member_by_email(self, email, key, value): """returns a job id""" if not value: raise FailedApiCall(Error('NO_VALUE_SET', 'No value provided'), self.client.server_name + '/apimember/services/MemberService?wsdl') data = u"""<?xml version="1.0" encoding="latin1" standalone="yes"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.service.apimember.emailvision.com/"> <soapenv:Header/> <soapenv:Body> <api:updateMember> <token>%s</token> <email>%s</email> <field>%s</field> <value>%s</value> </api:updateMember> </soapenv:Body> </soapenv:Envelope> """ % (self.token, email, key, value) response = self.post(data) r = response.soap_find('Body') r = r.find('{http://api.service.apimember.emailvision.com/}updateMemberResponse') r = r.find('return').text return r def retrieve_insert_member_job_status(self, job_id): # This does not work, it is always answering a 404. response = self.get('/apimember/services/rest/member/getInsertMemberStatus/', str(job_id)) return response def __build_member_attributes(self, attributes_node): attributes = dict() for entry in attributes_node.iterfind('entry'): key = entry.find('key').text value = None if entry.find('value') is not None: value = entry.find('value').text attributes[key] = value return attributes def iter_over_members_by_email(self, email): response = self.get('/apimember/services/rest/member/getMemberByEmail/', email) for member in response.find('members').iterfind('member'): yield self.__build_member_attributes(member.find('attributes')) def retrieve_member_by_id(self, id): response = self.get('/apimember/services/rest/member/getMemberById/', str(id)) attributes_nodes = response.find('apiMember').find('attributes') return self.__build_member_attributes(attributes_nodes) def iter_over_members_by_page(self, page): response = self.get('/apimember/services/rest/getListMembersByPage/', str(page)) for member in response.find('result').iterfind('list'): yield self.__build_member_attributes(member.find('attributes')) def member_table_column_names(self): response = self.get('/apimember/services/rest/member/descMemberTable/') entries = response.find('memberTable').find('fields').iterfind('entry') columns = dict() for entry in entries: key = entry.find('key').text value = entry.find('value').text columns[key] = value return columns def unsubscribe_members_by_email(self, email): """returns a job id""" response = self.get('/apimember/services/rest/member/unjoinByEmail/', email) return response.result def unsubscribe_members_by_id(self, id): """returns a job id""" response = self.get('/apimember/services/rest/member/unjoinByMemberId/', str(id)) return response.result def resubscribe_members_by_email(self, email): """returns a job id""" response = self.get('/apimember/services/rest/member/rejoinByEmail/', str(id)) return response.result def resubscribe_members_by_id(self, id): """returns a job id""" response = self.get('/apimember/services/rest/member/rejoinByMemberId/', str(id)) return response.result
class TestMultipleConnections(TestCase): def setUp(self) -> None: self.client_a = Client() self.client_b = Client() self.client_c = Client() self.client_a.connect() self.client_b.connect() self.client_c.connect() def tearDown(self) -> None: self.client_a.disconnect() self.client_b.disconnect() self.client_c.disconnect() @staticmethod def wrap_send(test_string: str, client: Client) -> dict: return { 'outgoing_message': test_string, 'returning_message': client.send(test_string) } def test_echo_3_connections(self) -> None: strings = generate_random_string(num_strings=3, len_strings=5) workers, results = [], [] with futures.ThreadPoolExecutor() as executor: workers.append( executor.submit(self.wrap_send, strings[0], self.client_a)) workers.append( executor.submit(self.wrap_send, strings[1], self.client_b)) workers.append( executor.submit(self.wrap_send, strings[2], self.client_c)) if futures.wait(workers, return_when=futures.FIRST_COMPLETED): for worker in workers: results.append(worker.result()) for result in results: with self.subTest(): self.assertEqual(result['outgoing_message'], result['returning_message'])
def wrap_send(test_string: str, client: Client) -> dict: return { 'outgoing_message': test_string, 'returning_message': client.send(test_string) }