Exemplo n.º 1
0
def test_wrap():
    abc = Abc({"name": "n", "val": 555})
    s = str(abc)

    def do_check(w):
        assert str(w.unwrap()) == s
        assert (
            str(w) ==
            '{"classRef": "hashkernel.tests.smattr_tests:Abc", "json": {"name": "n", "val": 555}}'
        )
        assert str(JsonWrap(to_json(w)).unwrap()) == s

    do_check(
        JsonWrap({
            "classRef": GlobalRef(Abc),
            "json": {
                "name": "n",
                "val": 555
            }
        }))
    do_check(JsonWrap.wrap(abc))
    try:
        JsonWrap.wrap(5)
    except AttributeError:
        assert "Not jsonable: 5" == exception_message()
Exemplo n.º 2
0
def test_reraise():
    class _Ex(Exception):
        def __init__(self, a, b):
            Exception.__init__(self, a + " " + b)

    for e_type in range(3):
        for i in range(2):
            try:
                try:
                    if e_type == 0:
                        raise ValueError("EOF")
                    elif e_type == 1:
                        raise _Ex("a", "EOF")
                    else:
                        eval("hello(")
                except:
                    if i == 0:
                        kernel.reraise_with_msg("bye")
                    else:
                        kernel.reraise_with_msg("bye", sys.exc_info()[1])
            except:
                e = sys.exc_info()[1]
                msg = kernel.exception_message(e)
                assert "EOF" in msg
                assert "bye" in msg
Exemplo n.º 3
0
def test_wiring():
    class Dependencies(AutoWire):
        _dependencies = []

        def add(self, depend_on: AutoWire) -> "Dependencies":
            self._dependencies.append(depend_on)
            return self

    x = Dependencies()

    z = x.y.z
    assert z._root() == None
    assert wire_names(z._path()) == ["", "y", "z"]

    class Dag(metaclass=AutoWireRoot):
        x = 3
        input = Dependencies()
        task1 = Dependencies().add(input.a)
        task2 = Dependencies().add(task1.input.v)
        output = Dependencies().add(task2.output.x)

    assert wire_names(Dag.input.a._path()) == ["input", "a"]
    assert wire_names(Dag.task1.input.v._path()) == ["task1", "input", "v"]

    assert Dag.input.a._root() == Dag
    assert Dag.task1.input.v._root() == Dag
    assert list(Dag._children.keys()) == ["input", "task1", "task2", "output"]

    try:
        q = x._q
        assert False
    except AttributeError:
        assert exception_message() == "no privates: _q"
Exemplo n.º 4
0
    def run(self, obj, call_name, params):
        call_meta = self.calls[call_name]
        converted = {}
        params_required = set(k for k in call_meta.params
                              if call_meta.params[k].required)
        for k in params:
            if k not in call_meta.params:
                raise TypeError('%s() does not have argument: %r' %
                                (call_name, k))
            param_meta = call_meta.params[k]
            converted[k] = param_meta.coerce_fn(params[k])
            if k in params_required:
                params_required.remove(k)

        if len(params_required) > 0:
            raise TypeError('%s() is missing required arguments: %r' %
                            (call_name, list(params_required)))
        try:
            r = getattr(obj, call_name)(**converted)
            return {'result': call_meta.coerce_return_fn(r)}
        except:
            log.exception(
                'exception on: {call_name}({params})'.format(**locals()))
            msg = exception_message()
            return {'error': call_meta.coerce_error_fn(msg)}
Exemplo n.º 5
0
def test_api():

    from hashstore.utils.api import ApiCallRegistry
    methods = ApiCallRegistry()

    class A:

        @methods.call(coerce_return_fn=lambda r: -r)
        def returns_5(self, a, b=4):
            '''
            documentation
            '''
            return 5

        @methods.call()
        def none(self):
            pass

        @methods.call(x=lambda i: i*i)
        def error(self, x):
            raise ValueError('%d' % x)

    eq_(set('returns_5 error none'.split()),set(methods.calls.keys()))
    eq_(methods.calls['returns_5'].doc.strip(),'documentation')
    a = A()
    try:
        methods.run(a, 'returns_5', {})
        ok_(False)
    except TypeError:
        eq_("returns_5() is missing required arguments: ['a']",
            exception_message())

    try:
        methods.run(a, 'returns_5', {'x':7})
        ok_(False)
    except TypeError:
        eq_("returns_5() does not have argument: 'x'",
            exception_message())

    eq_({'result': -5}, methods.run(a, 'returns_5', {'a': 7}))
    eq_({'error': '4'}, methods.run(a, 'error', {'x': 2}))
    eq_({'result': None}, methods.run(a, 'none', {}))
Exemplo n.º 6
0
def test_json_encode_decode():
    class q:
        pass

    try:
        kernel.json_encode(q())
        assert False
    except:
        assert "is not JSON serializable" in kernel.exception_message()

    assert (kernel.json_encode(
        datetime.datetime(2019, 4, 26, 19, 46, 50,
                          217946)) == '"2019-04-26T19:46:50.217946"')
    assert kernel.json_encode(datetime.date(2019, 4, 26)) == '"2019-04-26"'
    assert kernel.json_encode(JsonableExample("z", 5)) == '{"i": 5, "s": "z"}'
    assert kernel.json_decode('{"i": 5, "s": "z"}') == {"i": 5, "s": "z"}
    try:
        kernel.json_decode('{"i": 5, "s": "z"')
        assert False
    except ValueError:
        assert 'text=\'{"i": 5, "s": "z"\'' in kernel.exception_message()
Exemplo n.º 7
0
 def invoke(self, input: Dict[str, Any]) -> Generator[Any, None, None]:
     ctx = ExecContext(
         exec=self,
         invocation=QuestionMsg(ref=self.ref,
                                data=self.in_mold.mold_dict(
                                    input, Conversion.TO_JSON)),
     )
     yield ctx.invocation
     try:
         self.run(ctx)
     except:
         ctx.final_state = ResponseMsg(data={"msg": exception_message()},
                                       traceback=traceback.format_exc())
     yield ctx.final_state
Exemplo n.º 8
0
 def get(self, path):
     try:
         content = self.content(path)
         self.set_header('Content-Type', content.mime)
         if content.has_file() and os.name != 'nt':
             self.stream = PipeIOStream(content.open_fd())
             self.stream.read_until_close(callback=self.on_file_end,
                                          streaming_callback=self.on_chunk)
         else:
             self.finish(content.get_data())
     except NotAuthorizedError:
         self.write(exception_message())
         self.send_error(403)
     except FileNotFoundError:
         self.send_error(404)
     except:
         log.exception('error')
         self.send_error(500)
Exemplo n.º 9
0
    def initialize(self, store):
        self.store = store
        self._ctx = None

        session_id = self.request.headers.get('UserSession')
        no_session_in_headers = session_id is None or \
                                session_id == FROM_COOKIE
        if no_session_in_headers:
            session_id = self.get_cookie("UserSession")

        client_id = self.request.headers.get('ClientID')
        remote_ip = self.request.headers.get('X-Real-IP') or \
                    self.request.remote_ip
        self.ctx().params['remote_ip'] = remote_ip
        try:
            self.access = self.ctx().validate_session(session_id, client_id)
        except:
            log.debug(exception_message())
            self.access = GuestAccess(self.ctx())