Skip to content

Commit

Permalink
tests: add teamwork tests
Browse files Browse the repository at this point in the history
  • Loading branch information
daxartio committed Oct 15, 2023
1 parent ab72a79 commit 7287dcf
Show file tree
Hide file tree
Showing 14 changed files with 246 additions and 172 deletions.
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/course_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from sportorg.models.result.result_checker import ResultChecker
from sportorg.models.result.score_calculation import ScoreCalculation
from sportorg.models.result.split_calculation import RaceSplits
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork


class CourseEditDialog(BaseDialog):
Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/group_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from sportorg.models.memory import Limit, RaceType, find, race
from sportorg.models.result.result_calculation import ResultCalculation
from sportorg.modules.live.live import live_client
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork


class GroupEditDialog(BaseDialog):
Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/not_start_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from sportorg.models.memory import ResultManual, ResultStatus, find, race
from sportorg.models.result.result_calculation import ResultCalculation
from sportorg.modules.live.live import live_client
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork


class NotStartDialog(QDialog):
Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/organization_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sportorg.models.constant import get_countries, get_regions
from sportorg.models.memory import find, race
from sportorg.modules.live.live import live_client
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork


class OrganizationEditDialog(BaseDialog):
Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/person_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from sportorg.models.result.result_calculation import ResultCalculation
from sportorg.modules.configs.configs import Config
from sportorg.modules.live.live import live_client
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork


class PersonEditDialog(BaseDialog):
Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/dialogs/result_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from sportorg.models.result.result_checker import ResultChecker, ResultCheckerException
from sportorg.models.result.split_calculation import GroupSplits
from sportorg.modules.live.live import live_client
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork
from sportorg.utils.time import hhmmss_to_time


Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@
from sportorg.modules.sportident.sireader import SIReaderClient
from sportorg.modules.sportiduino.sportiduino import SportiduinoClient
from sportorg.modules.srpid.srpid import SrpidClient
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.packet_header import ObjectTypes
from sportorg.modules.teamwork.teamwork import Teamwork
from sportorg.modules.telegram.telegram import telegram_client


Expand Down
2 changes: 1 addition & 1 deletion sportorg/gui/menu/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
from sportorg.modules.sportident.sireader import SIReaderClient
from sportorg.modules.sportiduino.sportiduino import SportiduinoClient
from sportorg.modules.srpid.srpid import SrpidClient
from sportorg.modules.teamwork import Teamwork
from sportorg.modules.teamwork.teamwork import Teamwork
from sportorg.modules.telegram.telegram import telegram_client
from sportorg.modules.updater import checker
from sportorg.modules.winorient import winorient
Expand Down
139 changes: 0 additions & 139 deletions sportorg/modules/teamwork/__init__.py
Original file line number Diff line number Diff line change
@@ -1,139 +0,0 @@
import logging
from queue import Empty, Queue
from threading import Event, main_thread

from PySide2.QtCore import QThread, Signal

from sportorg.common.broker import Broker
from sportorg.common.singleton import singleton

from .client import ClientThread
from .packet_header import Operations
from .server import Command, ServerThread


class ResultThread(QThread):
data_sender = Signal(object)

def __init__(self, queue, stop_event, logger=None):
super().__init__()
# self.setName(self.__class__.__name__)
self._queue = queue
self._stop_event = stop_event
self._logger = logger

def run(self):
self._logger.debug('Teamwork result start')
while True:
try:
cmd = self._queue.get(timeout=5)
self.data_sender.emit(cmd)

except Empty:
if not main_thread().is_alive() or self._stop_event.is_set():
break
except Exception as e:
self._logger.debug(str(e))
self._logger.debug('Teamwork result shutdown')


@singleton
class Teamwork:
def __init__(self):
self._in_queue = Queue()
self._out_queue = Queue()
self._stop_event = Event()
self.factory = {'client': ClientThread, 'server': ServerThread}
self._thread = None
self._result_thread = None
self._call_back = None
self._logger = logging.root

self.host = ''
self.port = 50010
self.token = ''
self.connection_type = 'client'

def set_call(self, value):
if self._call_back is None:
self._call_back = value
return self

def set_options(self, host, port, token, connection_type):
self.host = host
self.port = port
self.token = token
self.connection_type = connection_type

def _start_thread(self):
if self.connection_type not in self.factory.keys():
return
if self._thread is None:
self._thread = self.factory[self.connection_type](
(self.host, self.port),
self._in_queue,
self._out_queue,
self._stop_event,
self._logger,
)
self._thread.start()
elif not self._thread.is_alive():
self._thread = None
self._start_thread()

def _start_result_thread(self):
if self._result_thread is None:
self._result_thread = ResultThread(
self._out_queue, self._stop_event, self._logger
)
if self._call_back is not None:
self._result_thread.data_sender.connect(self._call_back)
self._result_thread.start()
# elif not self._result_thread.is_alive():
elif self._result_thread.isFinished():
self._result_thread = None
self._start_result_thread()

def is_alive(self):
return (
self._thread is not None
and self._thread.is_alive()
and self._result_thread is not None
and not self._result_thread.isFinished()
)

def stop(self):
self._stop_event.set()

def start(self):
self._stop_event.clear()
self._in_queue.queue.clear()
self._out_queue.queue.clear()

self._start_thread()
self._start_result_thread()

def toggle(self):
if self.is_alive():
self.stop()
self._logger.info('{} stopping'.format(self.connection_type.upper()))
else:
self.start()
self._logger.info('{} starting'.format(self.connection_type.upper()))

def send(self, data, op=Operations.Update.name):
"""data is Dict or List[Dict]"""
if self.is_alive():
Broker().produce('teamwork_sending', data)
if isinstance(data, list):
for item in data:
self._in_queue.put(Command(item, op))
return

self._in_queue.put(Command(data, op))

def delete(self, data):
"""data is Dict or List[Dict]"""
Broker().produce('teamwork_deleting', data)
if self.is_alive():
pass
22 changes: 13 additions & 9 deletions sportorg/modules/teamwork/client.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import json
import queue
import socket
from threading import Thread, main_thread
from threading import Event, Thread, main_thread

import orjson

from .packet_header import Header, Operations
from .server import Command


class ClientSenderThread(Thread):
def __init__(self, conn, in_queue, stop_event, logger=None):
def __init__(self, conn, in_queue, stop_event, logger):
super().__init__(daemon=True)
self.setName(self.__class__.__name__)
self.conn = conn
Expand Down Expand Up @@ -37,7 +38,7 @@ def run(self):


class ClientReceiverThread(Thread):
def __init__(self, conn, out_queue, stop_event, logger=None):
def __init__(self, conn, out_queue, stop_event, logger):
super().__init__()
self.setName(self.__class__.__name__)
self.conn = conn
Expand All @@ -58,13 +59,11 @@ def run(self):
if not data:
break
full_data += data
# self._logger.debug('Client got data: {}'.format(full_data))
while True:
# getting Header
if is_new_pack:
if len(full_data) >= hdr.header_size:
hdr.unpack_header(full_data[: hdr.header_size])
# self._logger.debug('Client Packet Header: {}, ver: {}, size: {}'.format(full_data[:hdr.header_size], hdr.version, hdr.size))
full_data = full_data[hdr.header_size :]
is_new_pack = False
else:
Expand All @@ -73,7 +72,7 @@ def run(self):
else:
if len(full_data) >= hdr.size:
command = Command(
json.loads(full_data[: hdr.size].decode()),
orjson.loads(full_data[: hdr.size].decode()),
Operations(hdr.opType).name,
)
self._out_queue.put(command) # for local
Expand All @@ -98,16 +97,20 @@ def run(self):


class ClientThread(Thread):
def __init__(self, addr, in_queue, out_queue, stop_event, logger=None):
def __init__(self, addr, in_queue, out_queue, stop_event, logger):
super().__init__()
self.setName(self.__class__.__name__)
self.addr = addr
self._in_queue = in_queue
self._out_queue = out_queue
self._stop_event = stop_event
self._logger = logger
self._client_started = Event()

def run(self):
def join_client(self) -> None:
self._client_started.wait()

def run(self) -> None:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect(self.addr)
Expand All @@ -120,6 +123,7 @@ def run(self):
s, self._out_queue, self._stop_event, self._logger
)
receiver.start()
self._client_started.set()

sender.join()
receiver.join()
Expand Down
20 changes: 12 additions & 8 deletions sportorg/modules/teamwork/packet_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,25 @@ def __repr__(self):


"""
obj_type = ObjectTypes['Race']
obj_type.value
op = Operations['Create']
>>> Operations(0).name
```python
obj_type = ObjectTypes['Race']
obj_type.value
op = Operations['Create']
Operations(0).name
'Create'
```
"""

"""
```
?: boolean
H: Unsigned short
L: unsigned long
i: int
f: float
Q: Unsigned long long int
Q: Unsigned long long int
s: bytes string
Header Tag: 2 Bytes
Expand All @@ -66,6 +69,7 @@ def __repr__(self):
size: 8 Bytes (Unsigned Long long)
Total Header Size = 56 Bytes
```
"""


Expand Down Expand Up @@ -120,7 +124,7 @@ def prepare_header(self, obj_data, op_type):

try:
self.objType = ObjectTypes[obj_type].value
except:
except Exception:
self.objType = 255 # Unknown

self.uuid = obj_uuid
Expand Down
Loading

0 comments on commit 7287dcf

Please sign in to comment.