我正在尝试使用django频道的测试框架来测试我的消费者,但即使是基本的测试似乎也不起作用
这就是我的测试用例:
from channels import Channel
from channels.test import ChannelTestCase, HttpClient, apply_routes
from rci.consumers import Demultiplexer
from rosbridge.consumers import OtherWebSocketConsumer
class ChannelTestCase(ChannelTestCase):
def test_channel(self):
client = HttpClient()
client.send_and_consume('websocket.connect', '/new/') # <--- here's the error
self.assertIsNone(client.receive())
这是我的路线:
http_routing = [
route("http.request", admin.site.urls, path=r"^/admin/", method=r"^$"),
#...and so on
]
channel_routing = [Demultiplexer.as_route(path=r"^/sock/")]
这是我的消费者:
class Demultiplexer(WebsocketDemultiplexer):
channel_session_user = True
consumers = {
"rosbridge": ROSWebSocketConsumer,
"setting": SettingsConsumer,
}
这给了我以下错误:
错误:test_ros_channel (robot_configuration_interface.tests.unit.test_channels.ROSChannelTestCase) -------------------------------------------------- -------------------- Traceback(最近一次调用最后一次):文件 test_ros_channel中的“/home/cjds/development/robot_configuration_interface/robot_configuration_interface/tests/unit/test_channels.py”,第36行 client.send_and_consume('websocket.connect','/ new /')文件“/usr/local/lib/python2.7/dist-packages/channels/test/http.py”,行 94,在send_and_consume中 self.send(频道,内容,文本,路径)文件“/usr/local/lib/python2.7/dist-packages/channels/test/http.py”,行 79,发送 content.setdefault('reply_channel',self.reply_channel)AttributeError:'str'对象没有属性'setdefault'
我正在尝试按照本教程进行操作:
http://channels.readthedocs.io/en/stable/testing.html#clients
答案 0 :(得分:2)
您正在使用两个位置参数调用send_and_consume
,这会在此调用中生效(这正是在此行执行期间发生错误的原因):
# AGAIN this is wrong code this is what is written in the question
# only difference is the naming of the (previously positional) arguments
client.send_and_consume(channel='websocket.connect', content='/new/')
以下是解释错误的原因:
但是,send_and_consume
的实施期望content
成为字典:
def send_and_consume(self, channel, content={}, text=None, path='/', fail_on_none=True, check_accept=True):
"""
Reproduce full life cycle of the message
"""
self.send(channel, content, text, path)
return self.consume(channel, fail_on_none=fail_on_none, check_accept=check_accept)
实施代码取自:https://github.com/django/channels/blob/master/channels/test/http.py#L92
请参阅https://channels.readthedocs.io/en/latest/topics/testing.html,如Paul Whipp的评论所述。