コード例 #1
0
 def setUpClass(cls):
     error_handler = ErrorHandler()
     v1 = V1(error_handler=error_handler, app=app)
     v1.game(controller=GameServerController)
     v1.modes(controller=GameModes)
     v1.health(controller=HealthCheck)
     v1.readiness(controller=Readiness)
コード例 #2
0
 def setUp(self):
     self.eh = ErrorHandler(module="TestFlaskControllers", )
     self.app = app.test_client()
     self.application = self.app.application
     c = Configurator()
     if self.application.config["PYTHON_VERSION_MAJOR"] < 3:
         self.json_raises = ValueError
     else:
         self.json_raises = json.JSONDecodeError
コード例 #3
0
 def test_he_check_error(self):
     eh = ErrorHandler(module="TEST",
                       method="TEST-METHOD",
                       level=logging.INFO)
     message = "Message for testing purposes only"
     exception = "IGNORE Testing"
     r = eh.error(status=404, message=message, exception=exception)
     r_data = json.loads(r.get_data())
     self.assertEqual(r_data["status"], 404)
     self.assertEqual(r_data["message"], message)
     self.assertEqual(r_data["exception"], exception)
コード例 #4
0
    def execute_load(self, app):
        if app is None:
            raise ValueError(
                "The Flask app must be passed to the Configurator")
        if not isinstance(app, Flask):
            raise TypeError("Expected a Flask object, received {0}".format(
                type(app)))

        self.app = app
        self.app.config["PYTHON_VERSION_MAJOR"] = sys.version_info[0]

        self.app.config["LOGGING_FORMAT"] = os.getenv(
            "logging_format",
            os.getenv("LOGGING_FORMAT",
                      "%(asctime)s %(levelname)s: %(message)s"))
        self.app.config["LOGGING_LEVEL"] = os.getenv(
            "logging_level", os.getenv("LOGGING_LEVEL", logging.INFO))

        self.error_handler = ErrorHandler(
            module="Configurator",
            method="__init__",
            level=self.app.config["LOGGING_LEVEL"],
            format=self.app.config["LOGGING_FORMAT"])

        self.error_handler.log(
            message="Initialized logging (level: {}, format: {})".format(
                self.app.config["LOGGING_LEVEL"],
                self.app.config["LOGGING_FORMAT"]),
            logger=logging.info)

        self.error_handler.log(message="Configuring environment variables.",
                               logger=logging.info)

        self.configuration = {}

        config_file = self._set_config(source=os.getenv, name="COWBULL_CONFIG")
        self.app.config["COWBULL_CONFIG"] = config_file

        self.error_handler.log(message="Loading configuration from: {}".format(
            config_file if config_file else "environment variables"))

        source = {}
        if config_file:
            _file = open(config_file, 'r')
            try:
                source = json.load(_file)
            except:
                raise
            finally:
                _file.close()

        self.load_variables(source=source)
コード例 #5
0
    def setUp(self):
        self.error_handler = ErrorHandler(module="TestErrorHandler",
                                          method="setUp")
        self.app = app.test_client()
        if app.config["PYTHON_VERSION_MAJOR"] < 3:
            self.logging_type = io.BytesIO
        else:
            self.logging_type = io.StringIO

        self.logger = self.error_handler.logger
        self.lhStdout = self.logger.handlers[0]

        self.current_log_level = self.logger.getEffectiveLevel()
        self.log_capture = self.logging_type()
        self.sh = logging.StreamHandler(stream=self.log_capture)

        self.logger.setLevel(logging.INFO)
        self.logger.addHandler(hdlr=self.sh)
        self.logger.removeHandler(self.lhStdout)
コード例 #6
0
 def test_eh_instantiation(self):
     eh = ErrorHandler(module="test_module", method="test_method")
     self.assertIsInstance(eh, ErrorHandler)
     self.assertEqual(eh.module, "test_module")
     self.assertEqual(eh.method, "test_method")
コード例 #7
0
 def __init__(self):
     self.handler = ErrorHandler(
         module="AbstractPersister",
         method="__init__",
     )
コード例 #8
0
from TestGameController import TestGameController
from TestGameObject import TestGameObject
from TestHelpers import TestHelpers
from TestPersister import TestPersister
from TestPersisterMongo import TestPersisterMongo
from TestPersisterRedis import TestPersisterRedis
from TestFlaskControllers import TestFlaskControllers
from TestHealthCheck import TestHealthCheck
from TestGameMode import TestGameMode
from TestGameModes import TestGameModes
from python_cowbull_server import app
from Routes.V1 import V1
from flask_helpers.ErrorHandler import ErrorHandler
from flask_controllers import GameServerController
from flask_controllers import HealthCheck
from flask_controllers import Readiness
from flask_controllers import GameModes

logging.disable(logging.CRITICAL)
error_handler = ErrorHandler()
v1 = V1(error_handler=error_handler, app=app)
v1.game(controller=GameServerController)
v1.modes(controller=GameModes)
v1.health(controller=HealthCheck)
v1.readiness(controller=Readiness)

if __name__ == '__main__':
    import xmlrunner
    unittest.main(testRunner=xmlrunner.XMLTestRunner(
        output='unittest-reports'))
コード例 #9
0
    def __init__(self, **kwargs):
        self.handler = ErrorHandler(module="PersistenceEngine",
                                    method="__init__")

        self.handler.log(message="Getting persistence engine arguments")
        engine_name = kwargs.get('engine_name', None)
        parameters = kwargs.get('parameters', None)

        if not engine_name:
            raise ValueError(
                "'engine_name' must be defined for the persistence engine")
        if not isinstance(parameters, dict):
            raise TypeError("'parameters' must be a dictionary of objects")

        self._engine_name = engine_name
        self._parameters = parameters
        self._persister = None

        # Step 1 - Build path
        self.handler.log(message="Build import path")
        cwd = getcwd()
        extension_path = "{}/{}".format(cwd, "PersistenceExtensions")
        self.handler.log(
            message="Added {} to import path".format(extension_path))

        path.append(extension_path)

        # Step 2 - get the persisters and choose the right one
        self.handler.log(message="Building persisters and validators")
        persisters = [
            filefound[:-3] for filefound in listdir(extension_path)
            if filefound.endswith(".py")
        ]
        validators = [filefound.lower() for filefound in persisters]
        self.handler.log(message="Persisters: {}".format(persisters))
        self.handler.log(message="Validators: {}".format(validators))

        try:
            self.handler.log(message="Set persister")
            self._engine_name = persisters[validators.index(self._engine_name)]

            self.handler.log(message="Importing Persister from {}".format(
                self._engine_name))
            self._persister = importlib.import_module(self._engine_name)

            self.handler.log(message="Persistence engine set to {}".format(
                self._engine_name))
        except ValueError:
            if self._engine_name.lower() == 'redis':
                self.handler.log(message="Redis selected")
            else:
                self.handler.log(
                    message="Persister {} not found, defaulting to Redis".
                    format(self._engine_name))

            self._engine_name = "RedisPersist"

            self.handler.log(message="Importing RedisPersist")
            from Persistence import Redis
            self._persister = Redis
            self.handler.log(message="Persistence engine defaulted to Redis")
        except Exception:
            raise

        if not issubclass(self._persister.Persister, AbstractPersister):
            raise TypeError(
                "The persister must be a subclass of an AbstractPersister!")
        else:
            self.handler.log(
                message=
                "{} validated as a concrete implementation of an AbstractPersister"
                .format(self._engine_name))

        self.handler.log(message="Instantiating Persister")
        self._persister = self._persister.Persister(**self._parameters)
        return
コード例 #10
0
 def test_he_bad_method(self):
     with self.assertRaises(TypeError):
         ErrorHandler(module="test_he", method=10, level=10)
コード例 #11
0
 def test_he_bad_module(self):
     with self.assertRaises(TypeError):
         ErrorHandler(module=-2, method="test_he_eh_init", level=10)
コード例 #12
0
 def test_he_eh_init(self):
     eh = ErrorHandler(module="test_he",
                       method="test_he_eh_init",
                       level=logging.ERROR)
     self.assertIsInstance(eh, ErrorHandler)
コード例 #13
0
 def test_he_check_warn(self):
     eh = ErrorHandler(module="TEST",
                       method="TEST-METHOD",
                       level=logging.ERROR)
     message = "Message for testing purposes only"
     eh.log(status=404, message=message, logger=logging.warning)
コード例 #14
0
 def test_he_type_error(self):
     eh = ErrorHandler(module="TEST",
                       method="TEST-METHOD",
                       level={"foobar": "logging.INFO"})
     self.assertEqual(eh.logger.level, logging.INFO)
コード例 #15
0
 def test_he_value_error(self):
     eh2 = ErrorHandler(module="TEST",
                        method="TEST-METHOD",
                        level="logging.INFO")
     self.assertEqual(eh2.logger.level, logging.INFO)