1# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5
6class FakeHost(object):
7    """A fake implementation of a lansim.host.Host object.
8
9    This class replaces the real Host class and should be used for unit testing.
10    """
11
12    def __init__(self, ip_addr):
13        self.ip_addr = ip_addr
14
15        # List of FakeSocket objects returned by socket()
16        self._sockets = []
17
18
19    def socket(self, family, sock_type):
20        """Creates a new FakeSocket and returns it.
21
22        @param family: The socket family, for example AF_INET.
23        @param sock_type: The socket type, for example SOCK_DGRAM.
24        @return: a FakeSocket object.
25        """
26        sock = FakeSocket(self, family, sock_type)
27        self._sockets.append(sock)
28        return sock
29
30
31class FakeSocket(object):
32    """A fake socket interface implementation.
33
34    This class implements a fake socket object as returned by the Host.socket()
35    method.
36    """
37
38    def __init__(self, host, family, sock_type):
39        self._host = host
40        self._family = family
41        self._sock_type = sock_type
42        self._bound = False
43
44
45    def listen(self, ip_addr, port, recv_callback):
46        """Bind and listen on the ip_addr:port.
47
48        The fake implementation only stores these value as members of the
49        FakeSocket to allow the test inspect those values.
50
51        @param ip_addr: Local destination ip_addr.
52        @param port: Local destination port number.
53        @param recv_callback: A callback function that accepts three
54        arguments, the received string, the sender IPv4 address and the
55        sender port number.
56        """
57        self._bound = True
58        self._bind_ip_addr = ip_addr
59        self._bind_port = port
60        self._bind_recv_callback = recv_callback
61
62