def test_laod_data_read_data(self): client1 = Client(self.host, self.port, timeout=5) client2 = Client(self.host, self.port, timeout=5) try: client1.put("k.1", 0.25, timestamp=1) client2.put("k.1", 2.156, timestamp=2) client1.put("k.1", 0.35, timestamp=3) client2.put("k.2", 30, timestamp=4) client1.put("k.2", 40, timestamp=5) client1.put("k.2", 41, timestamp=5) except Exception as err: self.assertTrue( False, f"Ошибка вызова client.put(...) {err.__class__}: {err}") expected_metrics = { "k.1": [(1, 0.25), (2, 2.156), (3, 0.35)], "k.2": [(4, 30.0), (5, 41.0)], } #import pdb; pdb.set_trace() metrics = client1.get("*") self.assertTrue(metrics == expected_metrics) expected_metrics = {"k.2": [(4, 30.0), (5, 41.0)]} metrics = client2.get("k.2") self.assertTrue(metrics == expected_metrics) expected_metrics = {} metrics = client1.get("k.3") self.assertTrue(metrics == expected_metrics)
def test_get_cmd_good_key(self): keys = ['cpu.usage', 'cpu.temp', 'mem.usage', '*'] client = Client() for key in keys: try: client.get(key) except ClientError: self.assertTrue(False)
def test_get_sends_byte_str_command(self): key = 'cpu.cpu' cmd_bytes = 'get {}\n'.format(key).encode() client = Client() #import pdb; pdb.set_trace() client.get(key) sock_instance = self.MockClass.return_value sock_instance.connect.assert_called() first_call = 0 positional_args = 0 call_args = sock_instance.sendall.call_args_list[first_call][ positional_args] sended_str = call_args[0] self.assertTrue(cmd_bytes == sended_str)
def test_get_parses_empty_metrics(self): key = '*' client = Client() server_response = 'ok\n\n'.encode() sock_instance = self.MockClass.return_value sock_instance.recv = unittest.mock.Mock(return_value=server_response) metrics_expected = {} #import pdb; pdb.set_trace() metrics_received = client.get(key) self.assertTrue(metrics_expected == metrics_received)
def test_get_parses_metrics2(self): key = '*' client = Client() server_response = 'ok\npalm.cpu 10.5 1501864247\neardrum.cpu 15.3 1501864259\npalm.cpu 8.3 1501864340\neardrum.memory 200 1501861111\n\n'.encode( ) sock_instance = self.MockClass.return_value sock_instance.recv = unittest.mock.Mock(return_value=server_response) metrics_expected = { 'palm.cpu': [(1501864247, 10.5), (1501864340, 8.3)], 'eardrum.memory': [(1501861111, 200)], 'eardrum.cpu': [(1501864259, 15.3)] } metrics_received = client.get(key) self.assertTrue(metrics_expected == metrics_received)
def test_get_parses_metrics(self): key = '*' client = Client() server_response = 'ok\ncpu.cpu 5 543543\ncpu.usage 3 4354325\n\n'.encode( ) sock_instance = self.MockClass.return_value sock_instance.recv = unittest.mock.Mock(return_value=server_response) metrics_expected = { 'cpu.cpu': [(543543, 5)], 'cpu.usage': [(4354325, 3)] } #import pdb; pdb.set_trace() metrics_received = client.get(key) self.assertTrue(metrics_expected == metrics_received)
def test_get_same_key_two_clients(self): client1 = Client(self.host, self.port, timeout=5) client2 = Client(self.host, self.port, timeout=5) command = 'some_key' data_1 = None data_2 = None try: data_1 = client1.get(command) data_2 = client1.get(command) except ClientError: print( 'Сервер вернул ответ на валидный запрос, который клиент определил, ' 'как не корректный.. ') except BaseException as err: self.assertTrue( False, f"Сервер должен поддерживать соединение с клиентом между запросами, " f"повторный запрос к серверу завершился ошибкой: {err.__class__}: {err}" ) self.assertTrue(data_1 == data_2 == {})
def get(self): client = Client() return client.get('accounts').json()
def get(self): client = Client() return client.get('user').json()
def test_get_cmd_bad_str_key(self): bad_keys = ['cpucpu', 'cpu cpu', 'cpu.cpu.cpu'] client = Client() for bad_key in bad_keys: metrics = client.get(bad_key) self.assertTrue(metrics == {})
class Interface: def __init__(self, chat_addr=None, server_port=None): if chat_addr is None and server_port is None: server_port, chat_addr = self.get_port_and_ip() self.buttons = [] self.root = None self.main_frame = None self.messages_box = None self.message_input_box = None self.client = None self.refresher = utils.Daemon(name='refreshing', target=self.refresh, timeout=0.1) self.users_list = None if server_port is None: self.close() return nickname = self.get_nickname() self.client = Client(nickname, chat_addr, server_port) @staticmethod def get_port_and_ip(): root = Tk() root.title('Чат') port, ip = None, None def create_new(): nonlocal port, ip, root, server_port_field try: port = int(server_port_field.get()) except ValueError: return ip = None root.destroy() def connect(): nonlocal root, port, ip try: port = int(server_port_field.get()) except ValueError: return try: ip = chat_ip_field.get(), int(chat_port_field.get()) except ValueError: return root.destroy() server_port_label = Label(root, text='Введите порт: ') server_port_label.focus_set() server_port_label.pack() server_port_field = Entry(root) server_port_field.insert(END, '9090') server_port_field.pack() button_create_new = Button(root, text='Создать', width=len('Создать') + 2, command=create_new) button_create_new.pack() button_create_new.pack_propagate(False) ip_label = Label(root, text='Введите IP: ') ip_label.focus_set() ip_label.pack() chat_ip_field = Entry(root) chat_ip_field.pack() port_label = Label(root, text='Введите порт подключения: ') port_label.pack() chat_port_field = Entry(root) chat_port_field.pack() button_connect = Button(root, text='Подключиться', width=len('Подключиться') + 2, command=connect) button_connect.pack() button_connect.pack_propagate(False) root.mainloop() return port, ip def init_UI(self): self.root = Tk() self.root.title('Чат') self.root.minsize(width=700, height=300) menu = Menu(self.root) self.root.config(menu=menu) settings = Menu(menu) menu.add_cascade(label='Настройки', menu=settings) settings.add_command(label='Сменить ник', command=self.change_nickname) self.users_list = UserList(self.root, self.client, width=200) self.users_list.pack(fill=Y, side=LEFT, anchor=SW) self.users_list.pack_propagate(0) self.main_frame = Frame(self.root, width=600, height=300) self.main_frame.pack(fill=BOTH, expand=1, side=LEFT, anchor=SW) self.root.protocol('WM_DELETE_WINDOW', self.close) self.messages_box = MessagesList(self.main_frame, height=7, width=30, font=('Times New Roman', 11)) self.messages_box.config(state=DISABLED) self.messages_box.pack(fill=BOTH, expand=1) self.message_input_box = InputBox(self.main_frame, height=3, width=30, font=('Times New Roman', 11), func=self.send) self.message_input_box.pack(fill=BOTH, expand=1) self.message_input_box.focus_set() self.make_button('Отправить', 0, 2, self.send) def make_button(self, text: str, x: int, y: int, command): button = Button(self.main_frame, text=text, width=len(text) + 2, command=command) button.pack() button.pack_propagate(False) self.buttons.append(button) return button def get_nickname(self) -> str: try: return NicknameBar().get() except GeneratorExit: if self.client is None or not self.client.nickname: self.close() def change_nickname(self, _=None): nickname = self.get_nickname() self.client.send_message(Message(MessageType.SHARED, 'Сменил ник на ' + nickname)) self.client.nickname = nickname # TODO critical section def send(self, _=None): beginning = '0.0' message = self.message_input_box.get(beginning, END) # TODO encapsulate self.message_input_box.delete(beginning, END) message = message.rstrip(u'\n') if message == '': return message = Message(MessageType.SHARED, message) self.client.send_message(message) def run(self): self.init_UI() self.client.run() self.refresher.run() self.users_list.run() self.root.mainloop() def refresh(self): message = self.client.get() if message is not None: self.get_message(message) def get_message(self, message: Message): nickname_start, nickname_end = message.get_nick_position() message = str(message) + '\n' self.messages_box.config(state=NORMAL) need_to_scroll = False if self.messages_box.yview()[1] > 0.9: need_to_scroll = True cur_line, cur_column = map(int, self.messages_box.index(END).split('.')) cur_line -= 1 self.messages_box.insert(END, message) self.messages_box.tag_add('nickname', '{}.{}'.format(cur_line, nickname_start), '{}.{}'.format(cur_line, nickname_end)) self.messages_box.tag_config('nickname', foreground='blue') self.messages_box.config(state=DISABLED) if need_to_scroll: self.messages_box.see(END) def close(self): self.refresher.stop() if self.users_list is not None: self.users_list.close() if self.root is not None: self.root.destroy() self.root.quit() if self.client is not None: self.client.close() sys.exit(0)
def get(self): client = Client() return client.get('time').json()