本文整理汇总了Python中katcp.testutils.DeviceTestServer.add_sensor方法的典型用法代码示例。如果您正苦于以下问题:Python DeviceTestServer.add_sensor方法的具体用法?Python DeviceTestServer.add_sensor怎么用?Python DeviceTestServer.add_sensor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类katcp.testutils.DeviceTestServer
的用法示例。
在下文中一共展示了DeviceTestServer.add_sensor方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_DeviceServer
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
class test_DeviceServer(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.server = DeviceTestServer('', 0)
def test_on_client_connect(self):
fake_sock = mock.Mock()
mock_conn = mock.Mock(
spec=katcp.server.ClientConnection(self.server._server, fake_sock))
self.server.BUILD_INFO = ('buildy', 1, 2, 'g')
self.server.VERSION_INFO = ('deviceapi', 5, 6)
# Hack around ioloop thread asserts
self.server._server.ioloop_thread_id = thread.get_ident()
# Test call
self.server.on_client_connect(mock_conn)
# we are expecting 3 inform messages
no_msgs = 3
self.assertEqual(mock_conn.inform.call_count, no_msgs)
# Get all the messages sent to _send_message
msgs = [str(call[0][0]) for call in mock_conn.inform.call_args_list]
katcp_version = __version__
self._assert_msgs_equal(msgs, (
r'#version-connect katcp-protocol 5.0-IM',
# Will have to be updated for every library version bump
r'#version-connect katcp-library katcp-python-%s' % katcp_version,
r'#version-connect katcp-device deviceapi-5.6 buildy-1.2g'))
def test_request_sensor_sampling_clear(self):
self.server.clear_strategies = mock.Mock()
start_thread_with_cleanup(self, self.server, start_timeout=1)
client_connection = ClientConnectionTest()
self.server.ioloop.make_current()
tf = self.server.handle_message(
client_connection, katcp.Message.request('sensor-sampling-clear'))
# tf may be a tornado (not thread-safe) future, so we wrap it in a thread-safe
# future object
f = Future()
self.server.ioloop.add_callback(gen.chain_future, tf, f)
f.result(timeout=1)
# Ensure that the tornado future has finished running its callbacks
self.server.sync_with_ioloop()
self._assert_msgs_equal(client_connection.messages, [
'!sensor-sampling-clear ok'])
self.server.clear_strategies.assert_called_once_with(client_connection)
def test_has_sensor(self):
self.assertFalse(self.server.has_sensor('blaah'))
self.server.add_sensor(katcp.Sensor.boolean('blaah', 'blaah sens'))
self.assertTrue(self.server.has_sensor('blaah'))
示例2: test_DeviceServer
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
class test_DeviceServer(unittest.TestCase, TestUtilMixin):
def setUp(self):
self.server = DeviceTestServer('', 0)
def test_on_client_connect(self):
conn = katcp.server.ClientConnectionTCP(self.server, 'fake-sock')
m_sm = self.server._send_message = mock.Mock()
self.server.BUILD_INFO = ('buildy', 1, 2, 'g')
self.server.VERSION_INFO = ('deviceapi', 5, 6)
self.server.on_client_connect(conn)
# we are expecting 3 inform messages
no_msgs = 3
self.assertEqual(m_sm.call_count, no_msgs)
# Check that calls were syntactically valid
self.assertEqual(m_sm.call_args_list,
[mock.call('fake-sock', mock.ANY)]*no_msgs)
# Get all the messages sent to _send_message
msgs = [str(call[0][1]) for call in m_sm.call_args_list]
self._assert_msgs_equal(msgs, (
r'#version-connect katcp-protocol 5.0-IM',
# Will have to be updated for every library version bump
r'#version-connect katcp-library katcp-python-0.5.4',
r'#version-connect katcp-device deviceapi-5.6 buildy-1.2g') )
def test_request_sensor_sampling_clear(self):
self.server.clear_strategies = mock.Mock()
client_connection = ClientConnectionTest()
self.server.handle_message(
client_connection, katcp.Message.request('sensor-sampling-clear'))
self._assert_msgs_equal(client_connection.messages, [
'!sensor-sampling-clear ok'])
self.server.clear_strategies.assert_called_once_with(client_connection)
def test_has_sensor(self):
self.assertFalse(self.server.has_sensor('blaah'))
self.server.add_sensor(katcp.Sensor.boolean('blaah', 'blaah sens'))
self.assertTrue(self.server.has_sensor('blaah'))
示例3: TestInspectingClientAsync
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
class TestInspectingClientAsync(tornado.testing.AsyncTestCase):
def setUp(self):
super(TestInspectingClientAsync, self).setUp()
self.server = DeviceTestServer('', 0)
start_thread_with_cleanup(self, self.server, start_timeout=1)
self.host, self.port = self.server.bind_address
self.client = InspectingClientAsync(self.host, self.port,
ioloop=self.io_loop)
self.io_loop.add_callback(self.client.connect)
@tornado.testing.gen_test
def test_simple_request(self):
"""Perform a basic request."""
yield self.client.until_synced()
reply, informs = yield self.client.simple_request('help', 'watchdog')
self.assertIn('ok', str(reply))
self.assertEquals(len(informs), 1)
@tornado.testing.gen_test
def test_sensor(self):
"""Access the sensor with the Async client."""
yield self.client.until_synced()
sensor_name = 'an.int'
sensor = yield self.client.future_get_sensor(sensor_name)
self.assertEquals(sensor.name, sensor_name)
self.assertEquals(sensor.stype, 'integer')
# Unknown sensor requests return a None.
sensor_name = 'thing.unknown_sensor'
sensor = yield self.client.future_get_sensor(sensor_name)
self.assertIsNone(sensor)
@tornado.testing.gen_test
def test_request_access(self):
"""Test access to requests."""
yield self.client.until_synced()
request_name = 'watchdog'
self.assertIn(request_name, self.client.requests)
request = yield self.client.future_get_request(request_name)
self.assertEqual(request.name, request_name)
self.assertTrue(request.description,
'Expected an description: got nothing.')
# Unknown request return a None.
request_name = 'watchcat'
self.assertNotIn(request_name, self.client.requests)
request = yield self.client.future_get_request(request_name)
self.assertIsNone(request)
@tornado.testing.gen_test
def test_sensor_add_remove(self):
"""Test a sensor being added and then remove it."""
yield self.client.until_synced()
sensor = DeviceTestSensor(Sensor.INTEGER, "another.int",
"An Integer.",
"count", [-5, 5], timestamp=time.time(),
status=Sensor.NOMINAL, value=3)
# Check that the sensor does not exist currently
self.assertNotIn(sensor.name, self.client.sensors)
# Add a sensor.
self.server.add_sensor(sensor)
self.server.mass_inform(Message.inform('interface-changed'))
# Do a blocking request to ensure #interface-changed has been received
yield self.client.simple_request('watchdog')
yield self.client.until_synced()
self.assertIn('another.int', self.client.sensors)
# Remove a sensor.
self.server.remove_sensor(sensor)
self.server.mass_inform(Message.inform('interface-changed'))
# Do a blocking request to ensure #interface-changed has been received
yield self.client.simple_request('watchdog')
yield self.client.until_synced()
self.assertNotIn('another.int', self.client.sensors)
@tornado.testing.gen_test
def test_request_add_remove(self):
"""Test a request being added and then remove it."""
yield self.client.until_synced()
def request_sparkling_new(self, req, msg):
"""A new command."""
return Message.reply(msg.name, "ok", "bling1", "bling2")
# Check that the request did not exist before
self.assertNotIn('sparkling-new', self.client.requests)
# Add a request.
self.server.request_sparkling_new = request_sparkling_new
self.server._request_handlers['sparkling-new'] = request_sparkling_new
self.server.mass_inform(Message.inform('interface-changed'))
# Do a blocking request to ensure #interface-changed has been received
#.........这里部分代码省略.........
示例4: test_KATCPClientResource_IntegratedTimewarp
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [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)
#.........这里部分代码省略.........
示例5: test_KATCPClientResource_Integrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
class test_KATCPClientResource_Integrated(tornado.testing.AsyncTestCase):
def setUp(self):
super(test_KATCPClientResource_Integrated, 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(timeout=1)
def test_requests(self):
DUT = yield self._get_DUT_and_sync(self.default_resource_spec)
# Check that all the test-device requests are listed
self.assertEqual(sorted(DUT.req),
sorted(n.replace('-', '_')
for n in self.server.request_names))
@tornado.testing.gen_test(timeout=1)
def test_active(self):
DUT = yield self._get_DUT_and_sync(self.default_resource_spec)
self.assertTrue(DUT.is_active(), 'Expect DUT to be active initialy')
reply = yield DUT.req.new_command()
self.assertTrue(reply.succeeded, 'Expect request to be succesful in active state')
# Set DUT to 'inactive'
DUT.set_active(False)
with self.assertRaises(resource.KATCPResourceInactive):
# Should raise if we attempt to do the request when inactive
yield DUT.req.new_command()
# Set DUT to back to 'active'
DUT.set_active(True)
reply = yield DUT.req.new_command()
self.assertTrue(reply.succeeded, 'Expect request to be succesful in active state')
@tornado.testing.gen_test(timeout=1)
def test_sensors(self):
DUT = yield self._get_DUT_and_sync(self.default_resource_spec)
# Check that all the test-device sensors are listed
self.assertEqual(sorted(DUT.sensor),
sorted(n.replace('-', '_').replace('.', '_')
for n in self.server.sensor_names))
@tornado.testing.gen_test(timeout=1)
def test_interface_change(self):
DUT = yield self._get_DUT_and_sync(self.default_resource_spec)
sensors_before = set(DUT.sensor)
reqs_before = set(DUT.req)
# 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
self.assertNotIn(resource.escape_name(sensor.name), sensors_before)
# 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 did not exist before
self.assertNotIn('sparkling-new', reqs_before)
# Issue #interface-changed
self.server.mass_inform(Message.inform('interface-changed'))
yield DUT.until_state('syncing')
yield DUT.until_state('synced')
# Check if sensor/request was added
self.assertEqual(set(DUT.sensor) - sensors_before, set(['another_int']))
self.assertEqual(set(DUT.req) - reqs_before, set(['sparkling_new']))
# And now remove them again
self.server._request_handlers.pop('sparkling-new')
self.server.remove_sensor('another.int')
# Issue #interface-changed
self.server.mass_inform(Message.inform('interface-changed'))
yield DUT.until_state('syncing')
yield DUT.until_state('synced')
# Check if sensor/request was removed
self.assertEqual(set(DUT.sensor), sensors_before)
self.assertEqual(set(DUT.req), reqs_before)
示例6: TestDeviceServerClientIntegrated
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
#.........这里部分代码省略.........
self.server.start(timeout=0.1, daemon=True)
self.assertTrue(self.server._thread.isDaemon())
def test_excepthook(self):
"""Test passing in an excepthook to server start method."""
exceptions = []
except_event = threading.Event()
def excepthook(etype, value, traceback):
"""Keep track of exceptions."""
exceptions.append(etype)
except_event.set()
self.server.stop(timeout=0.1)
self.server.join(timeout=1.5)
self.server.start(timeout=0.1, excepthook=excepthook)
# force exception by deleteing _running
old_running = self.server._running
try:
del self.server._running
except_event.wait(1.5)
self.assertEqual(exceptions, [AttributeError])
finally:
self.server._running = old_running
# close socket -- server didn't shut down correctly
self.server._sock.close()
self.server.stop(timeout=0.1)
self.server.join(timeout=1.5)
except_event.clear()
del exceptions[:]
self.server.start(timeout=0.1, excepthook=excepthook)
# force exception in sample reactor and check that it makes
# it back up
reactor = self.server._reactor
old_stop = reactor._stopEvent
try:
del reactor._stopEvent
reactor._wakeEvent.set()
except_event.wait(0.1)
self.assertEqual(exceptions, [AttributeError])
finally:
reactor._stopEvent = old_stop
# close socket -- server didn't shut down correctly
self.server._sock.close()
def test_sampling(self):
"""Test sensor sampling."""
get_msgs = self.client.message_recorder(
blacklist=self.BLACKLIST, replies=True)
self.client.wait_protocol(timeout=1)
self.client.request(katcp.Message.request(
"sensor-sampling", "an.int", "period", 1/32.))
# Wait for the request reply and for the sensor update messages to
# arrive. We expect update one the moment the sensor-sampling request is
# made, then four more over 4/32. of a second, resutling in 6
# messages. Wait half a period longer just to be sure we get everything.
self.assertTrue(get_msgs.wait_number(6, timeout=4.5/32.))
self.client.assert_request_succeeds("sensor-sampling", "an.int", "none")
# Wait for reply to above request
get_msgs.wait_number(7)
msgs = get_msgs()
updates = [x for x in msgs if x.name == "sensor-status"]
others = [x for x in msgs if x.name != "sensor-status"]
self.assertTrue(abs(len(updates) - 5) < 2,
"Expected 5 informs, saw %d." % len(updates))
self._assert_msgs_equal(others, [
r"!sensor-sampling[1] ok an.int period %s" % (1/32.),
r"!sensor-sampling[2] ok an.int none",
])
self.assertEqual(updates[0].arguments[1:],
["1", "an.int", "nominal", "3"])
## Now clear the strategies on this sensor
# There should only be on connection to the server, so it should be
# the test client
client_conn = self.server._sock_connections.values()[0]
self.server.clear_strategies(client_conn)
self.client.assert_request_succeeds("sensor-sampling", "an.int",
args_equal=["an.int", "none"])
# Check that we did not accidentally clobber the strategy datastructure
# in the proccess
self.client.assert_request_succeeds(
"sensor-sampling", "an.int", "period", 0.125)
def test_add_remove_sensors(self):
"""Test adding and removing sensors from a running device."""
an_int = self.server._sensors["an.int"]
self.server.remove_sensor(an_int)
self.server.add_sensor(an_int)
self.test_sampling()
示例7: TestDeviceServer
# 需要导入模块: from katcp.testutils import DeviceTestServer [as 别名]
# 或者: from katcp.testutils.DeviceTestServer import add_sensor [as 别名]
#.........这里部分代码省略.........
# check that client was removed
self.assertTrue(sock not in self.server._socks, "Expected %r to not be in %r" % (sock, self.server._socks))
def test_bad_server_socket(self):
"""Test what happens when select is called on a dead server socket."""
# wait for client to arrive
time.sleep(0.1)
# close socket while the server isn't looking
# then wait for the server to notice
sock = self.server._sock
sockname = sock.getsockname()
sock.close()
time.sleep(0.75)
# check that server restarted
self.assertTrue(sock is not self.server._sock, "Expected %r to not be %r" % (sock, self.server._sock))
self.assertEqual(sockname, self.server._sock.getsockname())
def test_daemon_value(self):
"""Test passing in a daemon value to server start method."""
self.server.stop(timeout=0.1)
self.server.join(timeout=1.0)
self.server.start(timeout=0.1, daemon=True)
self.assertTrue(self.server._thread.isDaemon())
def test_excepthook(self):
"""Test passing in an excepthook to server start method."""
exceptions = []
except_event = threading.Event()
def excepthook(etype, value, traceback):
"""Keep track of exceptions."""
exceptions.append(etype)
except_event.set()
self.server.stop(timeout=0.1)
self.server.join(timeout=1.5)
self.server.start(timeout=0.1, excepthook=excepthook)
# force exception by deleteing _running
old_running = self.server._running
try:
del self.server._running
except_event.wait(1.5)
self.assertEqual(exceptions, [AttributeError])
finally:
self.server._running = old_running
# close socket -- server didn't shut down correctly
self.server._sock.close()
self.server.stop(timeout=0.1)
self.server.join(timeout=1.5)
except_event.clear()
del exceptions[:]
self.server.start(timeout=0.1, excepthook=excepthook)
# force exception in sample reactor and check that it makes
# it back up
reactor = self.server._reactor
old_stop = reactor._stopEvent
try:
del reactor._stopEvent
reactor._wakeEvent.set()
except_event.wait(0.1)
self.assertEqual(exceptions, [AttributeError])
finally:
reactor._stopEvent = old_stop
# close socket -- server didn't shut down correctly
self.server._sock.close()
def test_sampling(self):
"""Test sensor sampling."""
self.client.request(katcp.Message.request("sensor-sampling", "an.int", "period", 100))
time.sleep(1.0)
self.client.request(katcp.Message.request("sensor-sampling", "an.int", "none"))
time.sleep(0.5)
msgs = self.client.messages()
updates = [x for x in msgs if x.name == "sensor-status"]
others = [x for x in msgs if x.name != "sensor-status"]
self.assertTrue(abs(len(updates) - 12) < 2, "Expected 12 informs, saw %d." % len(updates))
self._assert_msgs_equal(others, [
r"#version device_stub-0.1",
r"#build-state name-0.1",
r"!sensor-sampling ok an.int period 100",
r"!sensor-sampling ok an.int none",
])
self.assertEqual(updates[0].arguments[1:], ["1", "an.int", "nominal", "3"])
def test_add_remove_sensors(self):
"""Test adding and removing sensors from a running device."""
an_int = self.server._sensors["an.int"]
self.server.remove_sensor(an_int)
self.server.add_sensor(an_int)
self.test_sampling()