本文整理汇总了Python中katcp.testutils.DeviceTestServer.start方法的典型用法代码示例。如果您正苦于以下问题:Python DeviceTestServer.start方法的具体用法?Python DeviceTestServer.start怎么用?Python DeviceTestServer.start使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类katcp.testutils.DeviceTestServer
的用法示例。
在下文中一共展示了DeviceTestServer.start方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ThreadSafeKATCPClientResourceWrapper
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class test_ThreadSafeKATCPClientResourceWrapper(unittest.TestCase):
def setUp(self):
self.server = DeviceTestServer('', 0)
start_thread_with_cleanup(self, self.server)
self.ioloop_manager = ioloop_manager.IOLoopManager(managed_default=True)
self.io_loop = self.ioloop_manager.get_ioloop()
self.host, self.port = self.server.bind_address
self.default_resource_spec = dict(
name='thething',
address=self.server.bind_address,
controlled=True)
self.client_resource = resource_client.KATCPClientResource(
self.default_resource_spec)
self.client_resource.set_ioloop(self.io_loop)
self.io_loop.add_callback(self.client_resource.start)
self.ioloop_thread_wrapper = resource_client.IOLoopThreadWrapper(self.io_loop)
start_thread_with_cleanup(self, self.ioloop_manager, start_timeout=1)
self.ioloop_thread_wrapper.default_timeout = 1
self.DUT = resource_client.ThreadSafeKATCPClientResourceWrapper(
self.client_resource, self.ioloop_thread_wrapper)
self.DUT.until_synced()
def test_wrapped_timeout(self):
self.assertEqual(self.client_resource.state, 'synced')
# Test timeout
self.ioloop_thread_wrapper.default_timeout = 0.001
t0 = time.time()
with self.assertRaises(TimeoutError):
self.DUT.until_state('disconnected')
self.assertLess(time.time() - t0, 0.2)
# Now make sure we can actualy still wait on the state
self.ioloop_thread_wrapper.default_timeout = 1
self.server.stop()
self.server.join()
self.DUT.until_state('disconnected')
self.assertEqual(self.client_resource.state, 'disconnected')
self.server.start()
self.DUT.until_state('synced')
self.assertEqual(self.client_resource.state, 'synced')
def test_request(self):
reply = self.DUT.req.sensor_value('an.int')
last_server_msg = self.server.messages[-1]
self.assertTrue(reply.succeeded)
self.assertEqual(str(last_server_msg),
'?sensor-value[{}] an.int'.format(reply.reply.mid))
def test_sensor(self):
server_sensor = self.server.get_sensor('an.int')
reading = self.DUT.sensor.an_int.get_reading()
self.assertEqual(reading.value, server_sensor.read().value)
server_sensor.set_value(server_sensor.read().value + 5)
reading = self.DUT.sensor.an_int.get_reading()
self.assertEqual(reading.value, server_sensor.read().value)
示例2: test_AsyncClientIntegratedBase
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class test_AsyncClientIntegratedBase(TimewarpAsyncTestCase):
def setUp(self):
super(test_AsyncClientIntegratedBase, self).setUp()
self.server = DeviceTestServer('localhost', 0)
self.server.set_ioloop(self.io_loop)
self.server.set_concurrency_options(thread_safe=False, handler_thread=False)
self.server.start()
host, port = self.server.bind_address
logger.info('host, port: {}:{}'.format(host, port))
self.client = katcp.CallbackClient(host, port)
self.client.set_ioloop(self.io_loop)
示例3: test_AsyncClientIntegrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class test_AsyncClientIntegrated(tornado.testing.AsyncTestCase, TestUtilMixin):
def setUp(self):
super(test_AsyncClientIntegrated, self).setUp()
self.server = DeviceTestServer('', 0)
self.server.set_ioloop(self.io_loop)
self.server.set_concurrency_options(thread_safe=False, handler_thread=False)
self.server.start()
host, port = self.server.bind_address
self.client = katcp.CallbackClient(host, port)
self.client.set_ioloop(self.io_loop)
self.client.start()
@tornado.testing.gen_test
def test_future_request_simple(self):
yield self.client.until_connected()
reply, informs = yield self.client.future_request(Message.request('watchdog'))
self.assertEqual(len(informs), 0)
self.assertEqual(reply.name, "watchdog")
self.assertEqual(reply.arguments, ["ok"])
@tornado.testing.gen_test
def test_future_request_with_informs(self):
yield self.client.until_connected()
reply, informs = yield self.client.future_request(Message.request('help'))
self.assertEqual(reply.name, "help")
self.assertEqual(reply.arguments, ["ok", "%d" % NO_HELP_MESSAGES])
self.assertEqual(len(informs), NO_HELP_MESSAGES)
@tornado.testing.gen_test
def test_disconnect_cleanup(self):
yield self.client.until_protocol()
mid = 55
future_reply = self.client.future_request(Message.request(
'slow-command', 1, mid=mid))
# Force a disconnect
self.client._disconnect()
reply, informs = yield future_reply
self.assertEqual(reply, Message.reply(
'slow-command', 'fail', 'Connection closed before reply was received',
mid=mid))
@tornado.testing.gen_test
def test_stop_cleanup(self):
yield self.client.until_protocol()
mid = 564
future_reply = self.client.future_request(Message.request(
'slow-command', 1, mid=mid))
# Stop client
self.client.stop()
reply, informs = yield future_reply
self.assertEqual(reply, Message.reply(
'slow-command', 'fail', 'Client stopped before reply was received', mid=mid))
示例4: test_AsyncClientTimeoutsIntegrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class test_AsyncClientTimeoutsIntegrated(TimewarpAsyncTestCase):
def setUp(self):
super(test_AsyncClientTimeoutsIntegrated, self).setUp()
self.server = DeviceTestServer('', 0)
self.server.set_ioloop(self.io_loop)
self.server.set_concurrency_options(thread_safe=False, handler_thread=False)
self.server.start()
host, port = self.server.bind_address
self.client = katcp.CallbackClient(host, port)
self.client.set_ioloop(self.io_loop)
self.client.start()
@tornado.testing.gen_test(timeout=10)
# We are using time-warping, so the timeout should be longer than the fake-duration
def test_future_request_default_timeout(self):
# Test the default timeout of 5s
yield self._test_timeout(5)
@tornado.testing.gen_test()
def test_future_request_change_default_timeout(self):
self.client._request_timeout = 3
yield self._test_timeout(3)
@tornado.testing.gen_test()
def test_future_request_request_timeout(self):
yield self._test_timeout(1, set_request_timeout=True)
@gen.coroutine
def _test_timeout(self, timeout, set_request_timeout=False):
request_timeout = timeout if set_request_timeout else None
yield self.client.until_connected()
t0 = self.io_loop.time()
reply_future = self.client.future_request(Message.request('slow-command', timeout + 1),
timeout=request_timeout)
# Warp to just before the timeout expires and check that the future is not yet
# resolved
self.set_ioloop_time(t0 + timeout*0.9999)
yield self.wake_ioloop()
self.assertFalse(reply_future.done())
# Warp to just after the timeout expires, and check that it gives us a timeout
# error reply
self.set_ioloop_time(t0 + timeout*1.0001)
yield self.wake_ioloop()
self.assertTrue(reply_future.done())
reply, informs = reply_future.result()
self.assertFalse(reply.reply_ok())
self.assertRegexpMatches(
reply.arguments[1],
r"Request slow-command timed out after .* seconds.")
示例5: TestBlockingClient
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestBlockingClient(unittest.TestCase):
def setUp(self):
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.client = katcp.BlockingClient(host, port)
self.client.start(timeout=0.1)
def tearDown(self):
if self.client.running():
self.client.stop()
self.client.join()
if self.server.running():
self.server.stop()
self.server.join()
def test_blocking_request(self):
"""Test blocking_request."""
reply, informs = self.client.blocking_request(
katcp.Message.request("watchdog"))
assert reply.name == "watchdog"
assert reply.arguments == ["ok"]
assert informs == []
reply, informs = self.client.blocking_request(
katcp.Message.request("help"))
assert reply.name == "help"
assert reply.arguments == ["ok", "13"]
assert len(informs) == int(reply.arguments[1])
def test_timeout(self):
"""Test calling blocking_request with a timeout."""
try:
self.client.blocking_request(
katcp.Message.request("slow-command", "0.5"),
timeout=0.001)
except RuntimeError, e:
self.assertEqual(str(e), "Request slow-command timed out after 0.001 seconds.")
else:
示例6: TestCallbackClient
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestCallbackClient(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.addCleanup(self.stop_server_client)
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.client = katcp.CallbackClient(host, port)
self.client.start(timeout=0.1)
self.assertTrue(self.client.wait_protocol(timeout=1))
def stop_server_client(self):
if hasattr(self, 'client') and self.client.running():
self.client.stop()
self.client.join()
if hasattr(self, 'server') and self.server.running():
self.server.stop()
self.server.join()
def test_callback_request(self):
"""Test callback request."""
watchdog_replies = []
watchdog_replied = threading.Event()
def watchdog_reply(reply):
self.assertEqual(reply.name, "watchdog")
self.assertEqual(reply.arguments, ["ok"])
watchdog_replies.append(reply)
watchdog_replied.set()
self.assertTrue(self.client.wait_protocol(0.2))
self.client.callback_request(
katcp.Message.request("watchdog"),
reply_cb=watchdog_reply,
)
watchdog_replied.wait(0.2)
self.assertTrue(watchdog_replies)
help_replies = []
help_informs = []
help_replied = threading.Event()
def help_reply(reply):
self.assertEqual(reply.name, "help")
self.assertEqual(reply.arguments, ["ok", "%d" % NO_HELP_MESSAGES])
self.assertEqual(len(help_informs), int(reply.arguments[1]))
help_replies.append(reply)
help_replied.set()
def help_inform(inform):
self.assertEqual(inform.name, "help")
self.assertEqual(len(inform.arguments), 2)
help_informs.append(inform)
self.client.callback_request(
katcp.Message.request("help"),
reply_cb=help_reply,
inform_cb=help_inform,
)
help_replied.wait(1)
self.assertTrue(help_replied.isSet())
help_replied.clear()
help_replied.wait(0.05) # Check if (unwanted) late help replies arrive
self.assertFalse(help_replied.isSet())
self.assertEqual(len(help_replies), 1)
self.assertEqual(len(help_informs), NO_HELP_MESSAGES)
def test_callback_request_mid(self):
## Test that the client does the right thing with message identifiers
# Wait for the client to detect the server protocol. Server should
# support message identifiers
self.assertTrue(self.client.wait_protocol(0.2))
# Replace send_message so that we can check the message
self.client.send_message = mock.Mock()
# By default message identifiers should be enabled, and should start
# counting at 1
self.client.callback_request(katcp.Message.request('watchdog'))
self.client.callback_request(katcp.Message.request('watchdog'))
self.client.callback_request(katcp.Message.request('watchdog'))
# Extract katcp.Message object .mid attributes from the mock calls to
# send_message
mids = [args[0].mid # arg[0] should be the Message() object
for args, kwargs in self.client.send_message.call_args_list]
self.assertEqual(mids, ['1','2','3'])
self.client.send_message.reset_mock()
# Explicitly ask for no mid to be used
self.client.callback_request(
katcp.Message.request('watchdog'), use_mid=False)
mid = self.client.send_message.call_args[0][0].mid
self.assertEqual(mid, None)
# Ask for a specific mid to be used
#.........这里部分代码省略.........
示例7: TestDeviceClientIntegrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestDeviceClientIntegrated(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.client = katcp.DeviceClient(host, port)
self.client.start(timeout=0.1)
def tearDown(self):
if self.client.running():
self.client.stop()
self.client.join()
if self.server.running():
self.server.stop()
self.server.join()
def test_request(self):
"""Test request method."""
self.assertTrue(self.client.wait_protocol(1))
self.client.send_request(katcp.Message.request("watchdog"))
self.client.send_request(katcp.Message.request("watchdog", mid=55))
self.client._server_supports_ids = False
with self.assertRaises(katcp.core.KatcpVersionError):
self.client.send_request(katcp.Message.request("watchdog", mid=56))
time.sleep(0.1)
msgs = self.server.messages()
self._assert_msgs_equal(msgs, [
r"?watchdog",
r"?watchdog[55]",
])
def test_send_message(self):
"""Test send_message method."""
self.client.send_message(katcp.Message.inform("random-inform"))
time.sleep(0.1)
msgs = self.server.messages()
self._assert_msgs_equal(msgs, [
r"#random-inform",
])
def test_stop_and_restart(self):
"""Test stopping and then restarting a client."""
self.client.stop(timeout=0.1)
# timeout needs to be longer than select sleep.
self.client.join(timeout=1.5)
self.assertEqual(self.client._thread, None)
self.assertFalse(self.client._running.isSet())
self.client.start(timeout=0.1)
def test_is_connected(self):
"""Test is_connected method."""
self.assertTrue(self.client.is_connected())
self.server.stop(timeout=0.1)
# timeout needs to be longer than select sleep.
self.server.join(timeout=1.5)
self.assertFalse(self.client.is_connected())
def test_wait_connected(self):
"""Test wait_connected method."""
start = time.time()
self.assertTrue(self.client.wait_connected(1.0))
self.assertTrue(time.time() - start < 1.0)
self.server.stop(timeout=0.1)
# timeout needs to be longer than select sleep.
self.server.join(timeout=1.5)
start = time.time()
self.assertFalse(self.client.wait_connected(0.2))
self.assertTrue(0.15 < time.time() - start < 0.25)
def test_bad_socket(self):
"""Test what happens when select is called on a dead socket."""
# wait for client to connect
time.sleep(0.1)
# close socket while the client isn't looking
# then wait for the client to notice
sock = self.client._sock
sockname = sock.getpeername()
sock.close()
time.sleep(1.25)
# check that client reconnected
self.assertTrue(sock is not self.client._sock,
"Expected %r to not be %r" % (sock, self.client._sock))
self.assertEqual(sockname, self.client._sock.getpeername())
def test_daemon_value(self):
"""Test passing in a daemon value to client start method."""
self.client.stop(timeout=0.1)
# timeout needs to be longer than select sleep.
self.client.join(timeout=1.5)
self.client.start(timeout=0.1, daemon=True)
self.assertTrue(self.client._thread.isDaemon())
#.........这里部分代码省略.........
示例8: TestCallbackClient
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestCallbackClient(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.addCleanup(self.stop_server_client)
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server.bind_address
self.client = katcp.CallbackClient(host, port)
self.client.start(timeout=1)
self.assertTrue(self.client.wait_protocol(timeout=1))
def stop_server_client(self):
if hasattr(self, 'client') and self.client.running():
self.client.stop()
self.client.join()
if hasattr(self, 'server') and self.server.running():
self.server.stop()
self.server.join()
def test_callback_request(self):
"""Test callback request."""
watchdog_replies = []
watchdog_replied = threading.Event()
def watchdog_reply(reply):
self.assertEqual(reply.name, "watchdog")
self.assertEqual(reply.arguments, ["ok"])
watchdog_replies.append(reply)
watchdog_replied.set()
self.assertTrue(self.client.wait_protocol(0.5))
self.client.callback_request(
Message.request("watchdog"),
reply_cb=watchdog_reply,
)
watchdog_replied.wait(0.5)
self.assertTrue(watchdog_replies)
help_replies = []
help_informs = []
help_replied = threading.Event()
def help_reply(reply):
self.assertEqual(reply.name, "help")
self.assertEqual(reply.arguments, ["ok", "%d" % NO_HELP_MESSAGES])
self.assertEqual(len(help_informs), int(reply.arguments[1]))
help_replies.append(reply)
help_replied.set()
def help_inform(inform):
self.assertEqual(inform.name, "help")
self.assertEqual(len(inform.arguments), 2)
help_informs.append(inform)
self.client.callback_request(
Message.request("help"),
reply_cb=help_reply,
inform_cb=help_inform,
)
help_replied.wait(1)
self.assertTrue(help_replied.isSet())
help_replied.clear()
help_replied.wait(0.05) # Check if (unwanted) late help replies arrive
self.assertFalse(help_replied.isSet())
self.assertEqual(len(help_replies), 1)
self.assertEqual(len(help_informs), NO_HELP_MESSAGES)
def test_callback_request_mid(self):
## Test that the client does the right thing with message identifiers
# Wait for the client to detect the server protocol. Server should
# support message identifiers
self.assertTrue(self.client.wait_protocol(0.2))
# Replace send_message so that we can check the message
self.client.send_message = mock.Mock(wraps=self.client.send_message)
# By default message identifiers should be enabled, and should start
# counting at 1
cb = counting_callback(number_of_calls=3)(lambda *x: x)
self.client.callback_request(Message.request('watchdog'), reply_cb=cb)
self.client.callback_request(Message.request('watchdog'), reply_cb=cb)
self.client.callback_request(Message.request('watchdog'), reply_cb=cb)
cb.assert_wait()
# Extract Message object .mid attributes from the mock calls to
# send_message
mids = [args[0].mid # args[0] should be the Message() object
for args, kwargs in self.client.send_message.call_args_list]
self.assertEqual(mids, ['1','2','3'])
self.client.send_message.reset_mock()
# Explicitly ask for no mid to be used
cb = counting_callback(number_of_calls=1)(lambda *x: x)
self.client.callback_request(
Message.request('watchdog'), use_mid=False, reply_cb=cb)
#.........这里部分代码省略.........
示例9: test_KATCPClientResource_IntegratedTimewarp
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class test_KATCPClientResource_IntegratedTimewarp(TimewarpAsyncTestCase):
def setUp(self):
super(test_KATCPClientResource_IntegratedTimewarp, self).setUp()
self.server = DeviceTestServer('', 0)
start_thread_with_cleanup(self, self.server)
self.host, self.port = self.server.bind_address
self.default_resource_spec = dict(
name='thething',
address=self.server.bind_address,
controlled=True)
@tornado.gen.coroutine
def _get_DUT_and_sync(self, resource_spec):
DUT = resource_client.KATCPClientResource(self.default_resource_spec)
DUT.start()
yield DUT.until_state('synced')
raise tornado.gen.Return(DUT)
@tornado.testing.gen_test
def test_disconnect(self):
# Test that a device disconnect / reconnect is correctly handled
DUT = yield self._get_DUT_and_sync(self.default_resource_spec)
initial_reqs = set(DUT.req)
initial_sensors = set(DUT.sensor)
self.server.stop()
self.server.join(timeout=1)
yield DUT.until_state('disconnected')
# Test that requests fail
rep = yield DUT.req.watchdog()
self.assertFalse(rep.succeeded)
# Restart device so that we can reconnect
self.server.start()
# timewarp beyond reconect delay
self.set_ioloop_time(self.ioloop_time + 1)
yield DUT.until_state('syncing')
yield DUT.until_state('synced')
# check that sensors / requests are unchanged
self.assertEqual(set(DUT.req), initial_reqs)
self.assertEqual(set(DUT.sensor), initial_sensors)
# Now disconnect and change the device, to check that it is properly resynced.
self.server.stop()
self.server.join(timeout=1)
yield DUT.until_state('disconnected')
# Add a new request to the server
def request_sparkling_new(self, req, msg):
"""A new command."""
return Message.reply(msg.name, "ok", "bling1", "bling2")
self.server._request_handlers['sparkling-new'] = request_sparkling_new
# Check that the request does not exist currently
self.assertNotIn('sparkling_new', initial_reqs)
# Add a new sensor to the server
sensor = DeviceTestSensor(DeviceTestSensor.INTEGER, "another.int",
"An Integer.",
"count", [-5, 5], timestamp=self.io_loop.time(),
status=DeviceTestSensor.NOMINAL, value=3)
self.server.add_sensor(sensor)
# Check that the sensor does not exist currently
escaped_new_sensor = resource.escape_name(sensor.name)
self.assertNotIn(resource.escape_name(sensor.name), initial_sensors)
# Restart device so that we can reconnect
self.server.start()
# timewarp beyond reconect delay
self.set_ioloop_time(self.ioloop_time + 1)
yield DUT.until_state('syncing')
yield DUT.until_state('synced')
# check that sensors / requests are correctly updated
self.assertEqual(set(DUT.req), initial_reqs | set(['sparkling_new']))
self.assertEqual(set(DUT.sensor), initial_sensors | set([escaped_new_sensor]))
@tornado.testing.gen_test(timeout=1000)
def test_set_sensor_sampling(self):
self.server.stop()
self.server.join()
DUT = resource_client.KATCPClientResource(self.default_resource_spec)
DUT.start()
yield tornado.gen.moment
test_strategy = ('period', '2.5')
yield DUT.set_sensor_strategy('an_int', test_strategy)
# Double-check that the sensor does not yet exist
self.assertNotIn('an_int', DUT.sensor)
self.server.start()
self.server.wait_running(timeout=1)
advancer = TimewarpAsyncTestCaseTimeAdvancer(self, quantum=0.55)
advancer.start()
yield DUT.until_synced()
self.assertEqual(DUT.sensor.an_int.sampling_strategy, test_strategy)
# Now call set_sensor_strategy with a different strategy and check that it is
# applied to the real sensor
new_test_strategy = ('event',)
yield DUT.set_sensor_strategy('an_int', new_test_strategy)
self.assertEqual(DUT.sensor.an_int.sampling_strategy, new_test_strategy)
@tornado.testing.gen_test(timeout=1000)
#.........这里部分代码省略.........
示例10: TestDeviceServerClientIntegrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestDeviceServerClientIntegrated(unittest.TestCase, TestUtilMixin):
BLACKLIST = ("version-connect", "version", "build-state")
def setUp(self):
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.server_addr = (host, port)
self.client = BlockingTestClient(self, host, port)
self.client.start(timeout=0.1)
self.assertTrue(self.client.wait_protocol(timeout=0.1))
def tearDown(self):
if self.client.running():
self.client.stop()
self.client.join()
if self.server.running():
self.server.stop()
self.server.join()
def test_log(self):
get_msgs = self.client.message_recorder(
blacklist=self.BLACKLIST,
replies=True)
with mock.patch('katcp.server.time.time') as m_time:
m_time.return_value = 1234
self.server.log.error('An error')
get_msgs.wait_number(1)
self._assert_msgs_equal(
get_msgs(), [r"#log error 1234.000000 root An\_error"])
def test_simple_connect(self):
"""Test a simple server setup and teardown with client connect."""
get_msgs = self.client.message_recorder(
blacklist=self.BLACKLIST,
replies=True)
# basic send
self.client.request(katcp.Message.request("foo"), use_mid=False)
# pipe-lined send
self.client.raw_send("?bar-boom\r\n?baz\r")
# broken up sends
self.client.raw_send("?boo")
self.client.raw_send("m arg1 arg2")
self.client.raw_send("\n")
time.sleep(0.1)
self._assert_msgs_equal(get_msgs(), [
r"!foo invalid Unknown\_request.",
r"!bar-boom invalid Unknown\_request.",
r"!baz invalid Unknown\_request.",
r"!boom invalid Unknown\_request.",
])
def test_bad_requests(self):
"""Test request failure paths in device server."""
get_msgs = self.client.message_recorder(
blacklist=self.BLACKLIST, replies=True)
self.client.raw_send("bad msg\n")
# wait for reply
self.client.blocking_request(
katcp.Message.request("watchdog"), use_mid=False)
self._assert_msgs_like(get_msgs(), [
(r"#log error", "KatcpSyntaxError:"
"\_Bad\_type\_character\_'b'.\\n"),
(r"!watchdog ok", ""),
])
def test_slow_client(self):
# Test that server does not choke sending messages to slow clients
self.server.send_timeout = 0.1 # Set a short sending timeout
self.client.wait_protocol(1)
slow_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
slow_sock.connect(self.server_addr)
slow_sock.settimeout(0.1)
# Send a bunch of request to the server, but don't read anything from
# the server
try:
slow_sock.sendall('?help\n'*100000)
except socket.timeout:
pass
t0 = time.time()
# Request should not have taken a very long time.
self.client.assert_request_succeeds('help', informs_count=NO_HELP_MESSAGES)
self.assertTrue(time.time() - t0 < 1)
def test_server_ignores_informs_and_replies(self):
"""Test server ignores informs and replies."""
get_msgs = self.client.message_recorder(
blacklist=self.BLACKLIST, replies=True)
self.client.raw_send("#some inform\n")
#.........这里部分代码省略.........
示例11: cb
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
from tornado.util import ObjectDict
from tornado.concurrent import Future as tornado_Future
from katcp import Sensor
from katcp.testutils import DeviceTestServer
from katcp.client import *
logging.basicConfig(
format="%(asctime)s %(name)s %(levelname)s %(funcName)s(%(filename)s:%(lineno)d)%(message)s",
level=logging.DEBUG
)
def cb(*args):
print args
try:
d = DeviceTestServer('', 0)
d.start(timeout=1)
logging.info('Server started at port {0}'.format(d.bind_address[1]))
c = AsyncClient('127.0.0.1', d.bind_address[1])
c.enable_thread_safety()
c.start(timeout=1)
# rm = Message.request
# #time.sleep(10000000)
import IPython ; IPython.embed()
finally:
d.stop()
c.stop()
示例12: TestCallbackClient
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestCallbackClient(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.client = CallbackTestClient(host, port)
self.client.start(timeout=0.1)
def tearDown(self):
if self.client.running():
self.client.stop()
self.client.join()
if self.server.running():
self.server.stop()
self.server.join()
def test_callback_request(self):
"""Test callback request."""
watchdog_replies = []
def watchdog_reply(reply):
self.assertEqual(reply.name, "watchdog")
self.assertEqual(reply.arguments, ["ok"])
watchdog_replies.append(reply)
self.client.request(
katcp.Message.request("watchdog"),
reply_cb=watchdog_reply,
)
time.sleep(0.1)
self.assertTrue(watchdog_replies)
help_replies = []
help_informs = []
def help_reply(reply):
self.assertEqual(reply.name, "help")
self.assertEqual(reply.arguments, ["ok", "13"])
self.assertEqual(len(help_informs), int(reply.arguments[1]))
help_replies.append(reply)
def help_inform(inform):
self.assertEqual(inform.name, "help")
self.assertEqual(len(inform.arguments), 2)
help_informs.append(inform)
self.client.request(
katcp.Message.request("help"),
reply_cb=help_reply,
inform_cb=help_inform,
)
time.sleep(0.2)
self.assertEqual(len(help_replies), 1)
self.assertEqual(len(help_informs), 13)
def test_no_callback(self):
"""Test request without callback."""
self.client.request(
katcp.Message.request("help")
)
time.sleep(0.1)
msgs = self.client.messages()
self._assert_msgs_like(msgs,
[("#version ", "")] +
[("#build-state ", "")] +
[("#help ", "")]*13 +
[("!help ok 13", "")]
)
def test_timeout(self):
"""Test requests that timeout."""
replies = []
informs = []
timeout = 0.001
def reply_cb(msg):
replies.append(msg)
def inform_cb(msg):
informs.append(msg)
self.client.request(
katcp.Message.request("slow-command", "0.1"),
reply_cb=reply_cb,
inform_cb=inform_cb,
timeout=timeout,
)
time.sleep(0.2)
self.assertEqual(len(replies), 1)
self.assertEqual(len(informs), 0)
#.........这里部分代码省略.........
示例13: TestDeviceServer
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import start [as 别名]
class TestDeviceServer(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.server = DeviceTestServer('', 0)
self.server.start(timeout=0.1)
host, port = self.server._sock.getsockname()
self.client = BlockingTestClient(self, host, port)
self.client.start(timeout=0.1)
def tearDown(self):
if self.client.running():
self.client.stop()
self.client.join()
if self.server.running():
self.server.stop()
self.server.join()
def test_simple_connect(self):
"""Test a simple server setup and teardown with client connect."""
# basic send
self.client.request(katcp.Message.request("foo"))
# pipe-lined send
self.client.raw_send("?bar-boom\r\n?baz\r")
# broken up sends
self.client.raw_send("?boo")
self.client.raw_send("m arg1 arg2")
self.client.raw_send("\n")
time.sleep(0.1)
msgs = self.client.messages()
self._assert_msgs_equal(msgs, [
r"#version device_stub-0.1",
r"#build-state name-0.1",
r"!foo invalid Unknown\_request.",
r"!bar-boom invalid Unknown\_request.",
r"!baz invalid Unknown\_request.",
r"!boom invalid Unknown\_request.",
])
def test_bad_requests(self):
"""Test request failure paths in device server."""
self.client.raw_send("bad msg\n")
# wait for reply
self.client.blocking_request(katcp.Message.request("watchdog"))
msgs = self.client.messages()
self._assert_msgs_like(msgs, [
(r"#version device_stub-0.1", ""),
(r"#build-state name-0.1", ""),
(r"#log error", "KatcpSyntaxError:\_Bad\_type\_character\_'b'.\\n"),
(r"!watchdog ok", ""),
])
def test_server_ignores_informs_and_replies(self):
"""Test server ignores informs and replies."""
self.client.raw_send("#some inform\n")
self.client.raw_send("!some reply\n")
time.sleep(0.1)
msgs = self.client.messages()
self._assert_msgs_like(msgs, [
(r"#version device_stub-0.1", ""),
(r"#build-state name-0.1", ""),
])
def test_standard_requests(self):
"""Test standard request and replies."""
self.client.request(katcp.Message.request("watchdog"))
self.client.request(katcp.Message.request("restart"))
self.client.request(katcp.Message.request("log-level"))
self.client.request(katcp.Message.request("log-level", "trace"))
self.client.request(katcp.Message.request("log-level", "unknown"))
self.client.request(katcp.Message.request("help"))
self.client.request(katcp.Message.request("help", "watchdog"))
self.client.request(katcp.Message.request("help", "unknown-request"))
self.client.request(katcp.Message.request("client-list"))
self.client.request(katcp.Message.request("sensor-list"))
self.client.request(katcp.Message.request("sensor-list", "an.int"))
self.client.request(katcp.Message.request("sensor-list", "an.unknown"))
self.client.request(katcp.Message.request("sensor-value"))
self.client.request(katcp.Message.request("sensor-value", "an.int"))
self.client.request(katcp.Message.request("sensor-value", "an.unknown"))
self.client.request(katcp.Message.request("sensor-sampling", "an.int"))
self.client.request(katcp.Message.request("sensor-sampling", "an.int", "differential", "2"))
self.client.request(katcp.Message.request("sensor-sampling"))
self.client.request(katcp.Message.request("sensor-sampling", "an.unknown", "auto"))
self.client.blocking_request(katcp.Message.request("sensor-sampling", "an.int", "unknown"))
time.sleep(0.1)
self.server.log.trace("trace-msg")
self.server.log.debug("debug-msg")
self.server.log.info("info-msg")
self.server.log.warn("warn-msg")
self.server.log.error("error-msg")
#.........这里部分代码省略.........