Commit f49625ca authored by qsr's avatar qsr Committed by Commit bot

mojo: Add RunLoop::Current() and refactor unit tests.

R=sdefresne@chromium.org

Review URL: https://codereview.chromium.org/644773002

Cr-Commit-Position: refs/heads/master@{#299100}
parent 1bae0dca
...@@ -41,6 +41,7 @@ cdef extern from "mojo/public/cpp/utility/run_loop.h" nogil: ...@@ -41,6 +41,7 @@ cdef extern from "mojo/public/cpp/utility/run_loop.h" nogil:
void RunUntilIdle() except * void RunUntilIdle() except *
void Quit() void Quit()
void PostDelayedTask(CClosure&, int64_t) void PostDelayedTask(CClosure&, int64_t)
cdef CRunLoop CRunLoopCurrent "mojo::RunLoop::current"()
cdef extern from "mojo/public/cpp/environment/environment.h" nogil: cdef extern from "mojo/public/cpp/environment/environment.h" nogil:
......
...@@ -17,6 +17,9 @@ from cpython.buffer cimport PyObject_GetBuffer ...@@ -17,6 +17,9 @@ from cpython.buffer cimport PyObject_GetBuffer
from cpython.mem cimport PyMem_Malloc, PyMem_Free from cpython.mem cimport PyMem_Malloc, PyMem_Free
from libc.stdint cimport int32_t, int64_t, uint32_t, uint64_t, uintptr_t from libc.stdint cimport int32_t, int64_t, uint32_t, uint64_t, uintptr_t
import ctypes
import threading
def SetSystemThunks(system_thunks_as_object): def SetSystemThunks(system_thunks_as_object):
"""Bind the basic Mojo Core functions. """Bind the basic Mojo Core functions.
...@@ -711,10 +714,29 @@ class DuplicateSharedBufferOptions(object): ...@@ -711,10 +714,29 @@ class DuplicateSharedBufferOptions(object):
self.flags = DuplicateSharedBufferOptions.FLAG_NONE self.flags = DuplicateSharedBufferOptions.FLAG_NONE
# Keeps a thread local weak reference to the current run loop.
_RUN_LOOPS = threading.local()
cdef class RunLoop(object): cdef class RunLoop(object):
"""RunLoop to use when using asynchronous operations on handles.""" """RunLoop to use when using asynchronous operations on handles."""
cdef c_environment.CRunLoop c_run_loop cdef c_environment.CRunLoop* c_run_loop
def __init__(self):
assert not <uintptr_t>(c_environment.CRunLoopCurrent())
self.c_run_loop = new c_environment.CRunLoop()
_RUN_LOOPS.loop = id(self)
def __dealloc__(self):
del _RUN_LOOPS.loop
del self.c_run_loop
@staticmethod
def Current():
if hasattr(_RUN_LOOPS, 'loop'):
return ctypes.cast(_RUN_LOOPS.loop, ctypes.py_object).value
return None
def Run(self): def Run(self):
"""Run the runloop until Quit is called.""" """Run the runloop until Quit is called."""
......
...@@ -2,18 +2,16 @@ ...@@ -2,18 +2,16 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
import unittest import mojo_unittest
# pylint: disable=F0401 # pylint: disable=F0401
import mojo.embedder
from mojo import system from mojo import system
class AsyncWaitTest(unittest.TestCase): class AsyncWaitTest(mojo_unittest.MojoTestCase):
def setUp(self): def setUp(self):
mojo.embedder.Init() super(AsyncWaitTest, self).setUp()
self.loop = system.RunLoop()
self.array = [] self.array = []
self.handles = system.MessagePipe() self.handles = system.MessagePipe()
self.cancel = self.handles.handle0.AsyncWait(system.HANDLE_SIGNAL_READABLE, self.cancel = self.handles.handle0.AsyncWait(system.HANDLE_SIGNAL_READABLE,
...@@ -24,7 +22,7 @@ class AsyncWaitTest(unittest.TestCase): ...@@ -24,7 +22,7 @@ class AsyncWaitTest(unittest.TestCase):
self.cancel() self.cancel()
self.handles = None self.handles = None
self.array = None self.array = None
self.loop = None super(AsyncWaitTest, self).tearDown()
def _OnResult(self, value): def _OnResult(self, value):
self.array.append(value) self.array.append(value)
......
...@@ -4,8 +4,9 @@ ...@@ -4,8 +4,9 @@
import unittest import unittest
import mojo_unittest
# pylint: disable=F0401 # pylint: disable=F0401
import mojo.embedder
from mojo.bindings import messaging from mojo.bindings import messaging
from mojo import system from mojo import system
...@@ -19,11 +20,10 @@ class _ForwardingConnectionErrorHandler(messaging.ConnectionErrorHandler): ...@@ -19,11 +20,10 @@ class _ForwardingConnectionErrorHandler(messaging.ConnectionErrorHandler):
self._callback(result) self._callback(result)
class ConnectorTest(unittest.TestCase): class ConnectorTest(mojo_unittest.MojoTestCase):
def setUp(self): def setUp(self):
mojo.embedder.Init() super(ConnectorTest, self).setUp()
self.loop = system.RunLoop()
self.received_messages = [] self.received_messages = []
self.received_errors = [] self.received_errors = []
def _OnMessage(message): def _OnMessage(message):
...@@ -44,7 +44,7 @@ class ConnectorTest(unittest.TestCase): ...@@ -44,7 +44,7 @@ class ConnectorTest(unittest.TestCase):
def tearDown(self): def tearDown(self):
self.connector = None self.connector = None
self.handle = None self.handle = None
self.loop = None super(ConnectorTest, self).tearDown()
def testConnectorRead(self): def testConnectorRead(self):
self.handle.WriteMessage() self.handle.WriteMessage()
...@@ -134,11 +134,10 @@ class HeaderTest(unittest.TestCase): ...@@ -134,11 +134,10 @@ class HeaderTest(unittest.TestCase):
self.assertEqual(other_header.request_id, 0xdeadbeafdeadbeaf) self.assertEqual(other_header.request_id, 0xdeadbeafdeadbeaf)
class RouterTest(unittest.TestCase): class RouterTest(mojo_unittest.MojoTestCase):
def setUp(self): def setUp(self):
mojo.embedder.Init() super(RouterTest, self).setUp()
self.loop = system.RunLoop()
self.received_messages = [] self.received_messages = []
self.received_errors = [] self.received_errors = []
def _OnMessage(message): def _OnMessage(message):
...@@ -158,7 +157,7 @@ class RouterTest(unittest.TestCase): ...@@ -158,7 +157,7 @@ class RouterTest(unittest.TestCase):
def tearDown(self): def tearDown(self):
self.router = None self.router = None
self.handle = None self.handle = None
self.loop = None super(RouterTest, self).tearDown()
def testSimpleMessage(self): def testSimpleMessage(self):
header_data = messaging.MessageHeader(0, messaging.NO_FLAG).Serialize() header_data = messaging.MessageHeader(0, messaging.NO_FLAG).Serialize()
......
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
# pylint: disable=F0401
import mojo.embedder
import mojo.system as system
class MojoTestCase(unittest.TestCase):
def setUp(self):
mojo.embedder.Init()
self.loop = system.RunLoop()
def tearDown(self):
self.loop = None
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
# Use of this source code is governed by a BSD-style license that can be # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. # found in the LICENSE file.
import unittest import mojo_unittest
# pylint: disable=F0401 # pylint: disable=F0401
import mojo.embedder
from mojo import system from mojo import system
...@@ -15,28 +14,28 @@ def _Increment(array): ...@@ -15,28 +14,28 @@ def _Increment(array):
return _Closure return _Closure
class RunLoopTest(unittest.TestCase): class RunLoopTest(mojo_unittest.MojoTestCase):
def setUp(self):
mojo.embedder.Init()
def testRunLoop(self): def testRunLoop(self):
loop = system.RunLoop()
array = [] array = []
for _ in xrange(10): for _ in xrange(10):
loop.PostDelayedTask(_Increment(array)) self.loop.PostDelayedTask(_Increment(array))
loop.RunUntilIdle() self.loop.RunUntilIdle()
self.assertEquals(len(array), 10) self.assertEquals(len(array), 10)
def testRunLoopWithException(self): def testRunLoopWithException(self):
loop = system.RunLoop()
def Throw(): def Throw():
raise Exception("error") raise Exception("error")
array = [] array = []
loop.PostDelayedTask(Throw) self.loop.PostDelayedTask(Throw)
loop.PostDelayedTask(_Increment(array)) self.loop.PostDelayedTask(_Increment(array))
with self.assertRaisesRegexp(Exception, '^error$'): with self.assertRaisesRegexp(Exception, '^error$'):
loop.Run() self.loop.Run()
self.assertEquals(len(array), 0) self.assertEquals(len(array), 0)
loop.RunUntilIdle() self.loop.RunUntilIdle()
self.assertEquals(len(array), 1) self.assertEquals(len(array), 1)
def testCurrent(self):
self.assertEquals(system.RunLoop.Current(), self.loop)
self.loop = None
self.assertIsNone(system.RunLoop.Current())
...@@ -3,12 +3,11 @@ ...@@ -3,12 +3,11 @@
# found in the LICENSE file. # found in the LICENSE file.
import random import random
import sys
import time import time
import unittest
import mojo_unittest
# pylint: disable=F0401 # pylint: disable=F0401
import mojo.embedder
from mojo import system from mojo import system
DATA_SIZE = 1024 DATA_SIZE = 1024
...@@ -19,13 +18,7 @@ def _GetRandomBuffer(size): ...@@ -19,13 +18,7 @@ def _GetRandomBuffer(size):
return bytearray(''.join(chr(random.randint(0, 255)) for i in xrange(size))) return bytearray(''.join(chr(random.randint(0, 255)) for i in xrange(size)))
class BaseMojoTest(unittest.TestCase): class CoreTest(mojo_unittest.MojoTestCase):
def setUp(self):
mojo.embedder.Init()
class CoreTest(BaseMojoTest):
def testResults(self): def testResults(self):
self.assertEquals(system.RESULT_OK, 0) self.assertEquals(system.RESULT_OK, 0)
...@@ -300,11 +293,3 @@ class CoreTest(BaseMojoTest): ...@@ -300,11 +293,3 @@ class CoreTest(BaseMojoTest):
self.assertEquals(data, buf1.buffer) self.assertEquals(data, buf1.buffer)
self.assertEquals(data, buf2.buffer) self.assertEquals(data, buf2.buffer)
self.assertEquals(buf1.buffer, buf2.buffer) self.assertEquals(buf1.buffer, buf2.buffer)
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(CoreTest)
test_results = unittest.TextTestRunner(verbosity=0).run(suite)
if not test_results.wasSuccessful():
sys.exit(1)
sys.exit(0)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment