def setUp(self):
        class TestHub(Hub):
            def __init__(self):
                super(TestHub, self).__init__()
                self.testFunctionReplayArg = lambda x: x
                self.testFunctionReplayNone = lambda: None

            def test_function_error(self):
                raise Exception("Error")

        class ClientMock:
            def __init__(self):
                self.writeMessage = flexmock()
                self.close = flexmock()
                pass

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.testHubClass = TestHub
        self.testHubInstance = HubsInspector.get_hub_instance(self.testHubClass)

        self.jsonPickler = Pickler(max_depth=3, max_iter=30, make_refs=False)
        self.commEnvironment = CommEnvironment(unprovided_id_template="unprovidedTest__{}")
        self.clientMock = ClientMock()
        self.connectedClient = ConnectedClient(self.commEnvironment, self.clientMock.writeMessage)
        self.connectedClientsHolder = ConnectedClientsHolder(self.testHubInstance)
        self.connectedClientsHolder.all_connected_clients.clear()
    def test_HubCreation_insertsInstanceInHUBs_DICT(self):
        class TestHub1(Hub):
            pass

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)

        self.assertTrue(HubsInspector.get_hub_instance(TestHub1) in HubsInspector.HUBS_DICT.values())
    def test_hub_creation_inserts_new__HubName__in_HUBS_DICT(self):
        class TestHub1(Hub):
            __HubName__ = "newValue"
            pass

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)

        self.assertIn("newValue", HubsInspector.HUBS_DICT.keys())
Example #4
0
    def setUp(self):
        global subprocess
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.serialMonitorHub = flexmock(HubsInspector.get_hub_instance(SerialMonitorHub))
        """:type : flexmock"""
        self.sender = create_sender_mock()

        self.compileUploaderMock, self.CompileUploaderConstructorMock = create_compiler_uploader_mock()
 def test_JAVACreation(self):
     path = "onTest"
     try:
         HubsInspector.construct_java_file("test", path)
         self.assertTrue(os.path.exists(os.path.join(path, JAVAFileGenerator.SERVER_FILE_NAME)))
         self.assertTrue(os.path.exists(os.path.join(path, JAVAFileGenerator.CLIENT_PACKAGE_NAME)))
     finally:
         for f in os.listdir(path):
             full_path = os.path.join(path, f)
             os.remove(full_path) if os.path.isfile(full_path) else shutil.rmtree(full_path)
Example #6
0
    def setUp(self):
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.hexFilePath = os.path.join(pm.TEST_SETTINGS_PATH, "CompilerUploader", "hex.hex")
        self.codeHub = HubsInspector.get_hub_instance(CodeHub)
        """:type : CodeHub"""

        self.sender = create_sender_mock()

        self.originalConstruct = CompilerUploader.construct
        self.compileUploaderMock, self.CompileUploaderConstructorMock = create_compiler_uploader_mock()
        self.board = CompilerUploader.DEFAULT_BOARD
Example #7
0
    def setUp(self):
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        Version.read_version_values()
        self.versionsHandlerHub = HubsInspector.get_hub_instance(VersionsHandlerHub)
        """ :type : VersionsHandlerHub"""
        self.libUpdater = self.versionsHandlerHub.lib_updater
        self.updater = self.versionsHandlerHub.w2b_updater
        self.sender = create_sender_mock()

        self.compileUploaderMock, self.CompileUploaderConstructorMock = create_compiler_uploader_mock()
        self.testLibVersion = "1.1.1"

        restore_test_resources()
Example #8
0
    def setUp(self):
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.hexFilePath = os.path.join(pm.TEST_SETTINGS_PATH,
                                        "CompilerUploader", "hex.hex")
        self.codeHub = HubsInspector.get_hub_instance(CodeHub)
        """:type : CodeHub"""

        self.sender = create_sender_mock()

        self.originalConstruct = CompilerUploader.construct
        self.compileUploaderMock, self.CompileUploaderConstructorMock = create_compiler_uploader_mock(
        )
        self.board = CompilerUploader.DEFAULT_BOARD
    def setUp(self):
        # Building hubs for testing
        class TestHub(Hub):
            def get_data(self):
                pass

        class TestHub2(Hub):
            pass

        self.resources_path = path_utils.get_resources_path("hubs_inspector")
        self.testHubClass = TestHub
        self.testHub2Class = TestHub2
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
    def test_PythonCreation_withClientFunctions(self):
        class TestHubWithClient(Hub):
            def get_data(self):
                pass

            def _define_client_functions(self):
                return dict(client1=lambda x, y: None,
                            client2=lambda x, y=1: None,
                            client3=lambda x=0, y=1: None)

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        HubsInspector.construct_python_file()

        self.assertTrue(os.path.exists(HubsInspector.DEFAULT_PY_API_FILE_NAME))
    def setUp(self):
        class TestHub(Hub):
            def test_method(self, x, _sender, y=1):
                return x, _sender, y

            def test_exception(self):
                raise Exception("MyException")

            def test_no_sender(self, x):
                return x

            def test_replay_unsuccessful(self, x):
                return self._construct_unsuccessful_replay(x)

        self.env_mock = flexmock(debug_mode=True)
        self.testHubClass = TestHub
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.testHubInstance = HubsInspector.get_hub_instance(self.testHubClass)
    def setUp(self):
        class TestHub(Hub):
            def get_data(self):
                pass

        class TestHub2(Hub):
            def get_data(self):
                pass

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
        self.other_folder = "onTest"
        self.other_name = "on_test"
        self.temp_folder = "__temp_folder__"
        self.original_working_directory = os.getcwd()
        if os.path.exists(self.temp_folder):
            shutil.rmtree(self.temp_folder)
        os.makedirs(self.temp_folder)
        os.chdir(self.temp_folder)
Example #13
0
 def emit(self, record):
     if '\n{"function": "onLoggingMessage"' in record.msg:
         return
     from libs.WSCommunication.Hubs.LoggingHub import LoggingHub
     r = getDecodedMessage(record, self)
     logging_hub = HubsInspector.get_hub_instance(LoggingHub)
     logging_hub.records_buffer.append(r)
     subscribedClients = logging_hub.clients.getSubscribedClients()
     subscribedClients.onLoggingMessage(datetime.now().isoformat(),
                                        r.levelno, r.msg, self.format(r))
    def test_getHubsInformation_ReturnsDictionaryWithClientFunctions(self):
        class TestHubWithClient(Hub):
            def get_data(self):
                pass

            def _define_client_functions(self):
                return dict(client1=lambda x, y: None,
                            client2=lambda x, y=1: None,
                            client3=lambda x=0, y=1: None)

        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)

        info_report = HubsInspector.get_hubs_information()

        self.assertIn("TestHubWithClient", info_report)
        client1method = info_report["TestHubWithClient"]["clientMethods"]["client1"]
        client2method = info_report["TestHubWithClient"]["clientMethods"]["client2"]
        client3method = info_report["TestHubWithClient"]["clientMethods"]["client3"]
        self.assertEqual(client1method["args"], ["x", "y"])
        self.assertEqual(client2method["defaults"], [1])
        self.assertEqual(client3method["defaults"], [0, 1])
Example #15
0
 def __construct_api_files():
     if not utils.are_we_frozen():
         HubsInspector.construct_js_file(path=os.path.join(
             "libs", "WSCommunication", "Clients", "hubsApi.js"))
         HubsInspector.construct_js_file(
             path=os.path.join(os.pardir, "demo", "_static", "hubsApi.js"))
         HubsInspector.construct_python_file(path=os.path.join(
             "libs", "WSCommunication", "Clients", "hubs_api.py"))
    def test_include_hubs_in_withOneModule(self):
        hubs_info = HubsInspector.get_hubs_information()
        self.assertNotIn("SubHub", hubs_info)

        HubsInspector.include_hubs_in(self.resources_path + os.sep + "one_module/*.py")
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)

        hubs_info = HubsInspector.get_hubs_information()
        self.assertIn("SubHub", hubs_info)
    def test_include_hubs_in_addsModulesIfPathIncluded(self):
        hubs_info = HubsInspector.get_hubs_information()
        self.assertNotIn("InPath1", hubs_info)
        self.assertNotIn("InPath2", hubs_info)

        HubsInspector.include_hubs_in(self.resources_path + os.sep + "in_path")
        HubsInspector.inspect_implemented_hubs(force_reconstruction=True)

        hubs_info = HubsInspector.get_hubs_information()
        self.assertIn("InPath1", hubs_info)
        self.assertIn("InPath2", hubs_info)
    def test_JSCreation_new_path(self):
        full_path = os.path.join(self.other_folder, self.other_name)
        HubsInspector.construct_js_file(full_path)

        self.assertTrue(os.path.exists(full_path))
    def test_JSCreation_default_path(self):
        HubsInspector.construct_js_file()

        self.assertTrue(os.path.exists(HubsInspector.DEFAULT_JS_API_FILE_NAME))
Example #20
0
class MyConnectionHandler(ConnectionHandler):
    executor = ThreadPoolExecutor()

    def open(self, name=None):
        client_id = name
        if client_id in self.comm_environment.all_connected_clients:
            self.comm_environment.all_connected_clients.pop(client_id)
            try:
                self.close()
            except Exception:
                pass
        self.comm_environment.on_opened(self._connected_client, client_id)

        log.debug("open new connection with ID: {} ".format(client_id))

    def on_message(self, message):
        self.executor.submit(super().on_message, message)


if __name__ == '__main__':
    app = web.Application([
        (r'/(.*)', MyConnectionHandler),
    ])
    HubsInspector.include_hubs_in("**/*_hub.py")  # use glob path patterns
    HubsInspector.inspect_implemented_hubs()
    HubsInspector.construct_js_file("../web_client/services/hubsApi.js")
    log.debug("starting...")
    app.listen(8888)

    ioloop.IOLoop.instance().start()
Example #21
0
 def __construct_api_files():
     if not utils.are_we_frozen():
         HubsInspector.construct_js_file(path=os.path.join("libs", "WSCommunication", "Clients", "hubsApi.js"))
         HubsInspector.construct_js_file(path=os.path.join(os.pardir, "demo", "_static", "hubsApi.js"))
         HubsInspector.construct_python_file(path=os.path.join("libs", "WSCommunication", "Clients", "hubs_api.py"))
from wsgiref.simple_server import make_server

from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
from ws4py.server.wsgiutils import WebSocketWSGIApplication

from wshubsapi.connection_handlers.ws4py_handler import ConnectionHandler
from wshubsapi.hubs_inspector import HubsInspector

if __name__ == '__main__':
    HubsInspector.include_hubs_in("*_hub.py")  # use glob path patterns
    HubsInspector.inspect_implemented_hubs()  # setup api
    HubsInspector.construct_python_file("../Clients/_static/hubs_api.py")  # only if you will use a python client
    HubsInspector.construct_js_file("../Clients/_static/hubsApi.js")  # only if you will use a js client

    server = make_server('127.0.0.1', 8888, server_class=WSGIServer,
                         handler_class=WebSocketWSGIRequestHandler,
                         app=WebSocketWSGIApplication(handler_cls=ConnectionHandler))
    server.initialize_websockets_manager()
    server.serve_forever()
import json
import logging.config

from wshubsapi.hubs_inspector import HubsInspector
from wshubsapi.connection_handlers.socket_handler import create_socket_server

logging.config.dictConfig(json.load(open('logging.json')))
log = logging.getLogger(__name__)

if __name__ == '__main__':
    HubsInspector.include_hubs_in("*_hub.py")  # use glob path patterns
    # construct the necessary client files in the specified path
    HubsInspector.inspect_implemented_hubs()
    HubsInspector.construct_python_file("../Clients/_static/hubs_api.py")

    server = create_socket_server("127.0.0.1", 8890)

    server.serve_forever()


    def test_getHubsInformation_ReturnsDictionaryWithNoClientFunctions(self):
        hubs_info = HubsInspector.get_hubs_information()

        self.assertIn("TestHub2", hubs_info)
        self.assertIn("get_data", hubs_info["TestHub"]["serverMethods"])
Example #25
0
 def __init__(self):
     super(CodeHub, self).__init__()
     self.serial_hub = HubsInspector.get_hub_instance(SerialMonitorHub)
     """ :type : SerialMonitorHub"""
if os.path.exists('logging.json'):
    logging.config.dictConfig(json.load(open('logging.json')))
log = logging.getLogger(__name__)


def get_module_path():
    path = os.path.join(os.path.dirname(__file__))
    if not path.endswith("resources"):
        path = os.path.join(path, 'wshubsapi', 'test', 'integration', 'resources')
    return path


settings = {"static_path": join(get_module_path(), "clients_api")}

app = web.Application([
    (r'/(.*)', ConnectionHandler),
], **settings)

if __name__ == '__main__':
    # necessary to add this import for code inspection
    importlib.import_module("wshubsapi.test.integration.resources.hubs.chat_hub")
    importlib.import_module("wshubsapi.test.integration.resources.hubs.echo_hub")
    HubsInspector.inspect_implemented_hubs(force_reconstruction=True)
    HubsInspector.construct_js_file(settings["static_path"] + os.sep + "hubsApi.js")
    HubsInspector.construct_python_file(settings["static_path"] + os.sep + "hubs_api.py")
    log.debug("starting...")
    app.listen(11111)

    ioloop.IOLoop.instance().start()
    def test_PythonCreation_default_values(self):
        HubsInspector.construct_python_file()

        self.assertTrue(os.path.exists(HubsInspector.DEFAULT_PY_API_FILE_NAME))
        self.assertTrue(os.path.exists("__init__.py"), "Check if python package is created")
Example #28
0
from wshubsapi.hubs_inspector import HubsInspector

if __name__ == '__main__':
    HubsInspector.include_hubs_in("*_hub.py")  # use glob path patterns
    HubsInspector.inspect_implemented_hubs()
    HubsInspector.construct_python_file("module_api/hubs_api.py")
 def test_PythonCreation_new_path(self):
     full_path = os.path.join(self.other_folder, self.other_name)
     package_file_path = os.path.join(self.other_folder, "__init__.py")
     HubsInspector.construct_python_file(full_path)
     self.assertTrue(os.path.exists(full_path))
     self.assertTrue(os.path.exists(package_file_path), "Check if python package is created")
Example #30
0
    run_scons_script()
    os._exit(1)

if __name__ == "__main__":
    try:
        importlib.import_module("libs.WSCommunication.Hubs")
        from libs.MainApp import force_quit, MainApp
        app = MainApp()

        def close_sig_handler(signal, frame):
            try:
                log.warning("closing server")
                app.w2b_server.server_close()
                log.warning("server closed")
            except:
                log.warning("unable to close server")
            force_quit()
        HubsInspector.inspect_implemented_hubs()

        signal.signal(signal.SIGINT, close_sig_handler)
        app.start_main()
    except SystemExit:
        pass
    except Exception as e:
        if log is None:
            raise e
        else:
            log.critical("critical exception", exc_info=1)

    os._exit(1)
    def test_DartCreation_default_values(self):
        HubsInspector.construct_dart_file()

        self.assertTrue(os.path.exists(HubsInspector.DEFAULT_DART_API_FILE_NAME))
Example #32
0
 def __init__(self, *args, **kwargs):
     super(HubsHandler, self).__init__(*args, **kwargs)
     HubsInspector.inspect_implemented_hubs()
 def test_get_hubs_structure_returns_HubsInspector_get_hubs_information(self):
     self.assertEqual(self.utils_hub.get_hubs_structure(), HubsInspector.get_hubs_information())
import os
import logging.config
import json
from tornado import web, ioloop

from wshubsapi.hubs_inspector import HubsInspector
from wshubsapi.connection_handlers.tornado_handler import ConnectionHandler

logging.config.dictConfig(json.load(open('logging.json')))
log = logging.getLogger(__name__)

settings = {"static_path": os.path.join(os.path.dirname(__file__), "../Clients/_static")}

app = web.Application([
    (r'/(.*)', ConnectionHandler),
], **settings)

if __name__ == '__main__':
    HubsInspector.include_hubs_in("*_hub.py")  # use glob path patterns
    HubsInspector.inspect_implemented_hubs()
    HubsInspector.construct_js_file(settings["static_path"] + os.sep + "hubsApi.js")
    HubsInspector.construct_python_file(settings["static_path"] + os.sep + "hubs_api.py")
    HubsInspector.construct_dart_file(settings["static_path"] + os.sep + "hubs_api.dart")
    log.debug("starting...")
    app.listen(8888)

    ioloop.IOLoop.instance().start()
 def test_getHubInstance_returnsAnInstanceOfHubIfExists(self):
     self.assertIsInstance(HubsInspector.get_hub_instance(self.testHubClass), Hub)