Twisted deferred.callback(value) 使用 None 触发回调

Twisted deferred.callback(value) fires callback with None

正在为扭曲的应用程序编写单元测试。一旦延迟被新的(虚拟)连接(proto_helpers.StringTransport 的实例)解决,尝试执行一些断言,但是回调 assert_cache_updated_on_connection 正在接收 None 而不是 connection传递给 <deferred>.callback(connection)

def test_send_to_new_connection(self):
    # Given
    peerAddr = ('10.22.22.190', 5060)

    # If
    self.tcp_transport.send_to('test', peerAddr)

    # Then
    assert peerAddr in self.tcp_transport._connections
    assert True == isinstance(self.tcp_transport._connections[peerAddr], Deferred)

    connection = _string_transport_connection(self.hostAddr, peerAddr, None, self.tcp_transport.connectionMade)

    def assert_cache_updated_on_connection(connection):
        print('--------- SUCCESS ----------')
        peer = connection.transport.getPeer()
        peerAddr = (peer.host, peer.port)

        assert peerAddr in self.tcp_transport._connections
        assert True == isinstance(self.tcp_transport._connections[peerAddr], Protocol)

    def assert_fail(fail):
        print('--------- FAIL ----------')

    self.tcp_transport._connections[peerAddr].addCallback(assert_cache_updated_on_connection)
    self.tcp_transport._connections[peerAddr].addErrback(assert_fail)
    # Forcing deferred to fire with mock connection
    self.tcp_transport._connections[peerAddr].callback(connection)

这是手动触发延迟回调的正确方法吗?

回调接收以下两个参数之一作为其第一个参数:

  • 如果是第一个回调,它接收传递给callback方法的值。
  • 如果是后续回调,则接收之前回调的return值

所以大概的解释是 assert_cache_updated_on_connection 不是第一个回调,它之前的回调是 returning None.