예제 #1
0
def test_buffer_drains():
    buffer = RotatingBuffer()
    buffer.push(1)
    buffer.push(2)
    buffer.push(3)
    assert list(buffer) == [1, 2, 3]
    assert list(buffer) == []
예제 #2
0
def test_can_add_midway_through():
    buffer = RotatingBuffer()
    buffer.push(1)
    buffer.push(2)
    assert next(buffer) == 1
    buffer.push(3)
    assert list(buffer) == [2, 3]
예제 #3
0
파일: binding.py 프로젝트: kkrbalam/pyjq
 def __init__(self):
     self.compat = None
     self.recorder = recorder.current
     self.compat = self._invoke("jq_compat_new")
     self.pending_objects = RotatingBuffer()
     if self.recorder:
         self.recorder.record_new(self.compat)
예제 #4
0
파일: binding.py 프로젝트: kkrbalam/pyjq
class JQ(object):
    lib = ctypes.cdll.LoadLibrary(os.path.join(
        os.path.dirname(__file__),
        "compat.so"
    ))

    lib.jq_compat_new.restype = ctypes.c_size_t
    lib.jq_compat_compile.restype = int
    lib.jq_compat_read_error.restype = ctypes.c_char_p
    lib.jq_compat_read_output.restype = ctypes.c_char_p

    def __init__(self):
        self.compat = None
        self.recorder = recorder.current
        self.compat = self._invoke("jq_compat_new")
        self.pending_objects = RotatingBuffer()
        if self.recorder:
            self.recorder.record_new(self.compat)

    def __del__(self):
        if self.compat:
            self.invoke("del")
            self.compat = None

    def compile(self, program):
        with self.__check_error(JQParseError):
            self.invoke("compile", ctypes.c_char_p(program))

    def write(self, value):
        self.write_string(json.dumps(value))

    def write_string(self, s):
        with self.__check_error():
            self.invoke(
                "write",
                len(s),
                ctypes.c_char_p(s)
            )

    def __iter__(self):
        data = map(json.loads, str(self.invoke("read_output")).splitlines())
        for o in data:
            self.pending_objects.push(o)
        return self.pending_objects

    def invoke(self, name, *args):
        args = ((self.compat,) + args)
        name = "jq_compat_" + name
        if self.recorder:
            self.recorder.record(name, args)
        return self._invoke(name, *args)

    def _invoke(self, name, *args):
        return getattr(self.lib, name)(*args)

    @contextmanager
    def __check_error(self, exc=JQError):
        self.invoke("clear_error")
        yield
        if self.lib.jq_compat_had_error(self.compat):
            current_error = str(self.invoke("read_error"))
            raise exc(str(current_error))