1# Copyright 2019 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"""Tests for cfm_helper.py."""
5
6import unittest
7
8import cfm_helper
9import get_usb_devices
10
11SPEAKERS = 'speakers'
12CAMERAS = 'cameras'
13DISPLAY_MIMO = 'display_mimo'
14CONTROLLER_MIMO = 'controller_mimo'
15DEVICE_TYPES = (SPEAKERS, CAMERAS, DISPLAY_MIMO, CONTROLLER_MIMO)
16
17
18class TestExtractPeripherals(unittest.TestCase):
19    """Test cfm_helper.extract_peripherals()"""
20
21    def create_mock_device_getter(self, device_list):
22        """Mock a function to take usb_data and return device_list"""
23
24        def mock_device_getter(usb_data):
25            """Return the specified device_list, ignoring usb_data."""
26            return device_list
27
28        return mock_device_getter
29
30    def setUp(self):
31        """
32        Mock the various get_devices functions so that each one returns a
33        key-value pair.
34        In extract_peripherals(), the key represents the pid_vid, and the value
35        represents the device_count.
36        For these testing purposes, we use the device_type ('cameras', etc.)
37        as the key, and a number 1-4 as the device_count.
38        (If we used a device_count of 0 it would be ignored; hence, 1-4.)
39
40        """
41        self.original_funcs = {}
42        for i in range(len(DEVICE_TYPES)):
43            device_type = DEVICE_TYPES[i]
44            mock = self.create_mock_device_getter({device_type: i + 1})
45            setattr(cfm_helper.get_usb_devices, 'get_%s' % device_type, mock)
46
47    def runTest(self):
48        """Verify that all 4 peripheral-types are extracted."""
49        peripherals = cfm_helper.extract_peripherals_for_cfm(None)
50        self.assertEqual(len(peripherals), 4)
51        for i in range(len(DEVICE_TYPES)):
52            device_type = DEVICE_TYPES[i]
53            self.assertEqual(peripherals[device_type], i + 1)
54
55    def tearDown(self):
56        """Restore the original functions, for the sake of other tests."""
57        for device_type in DEVICE_TYPES:
58            original_func = getattr(get_usb_devices, 'get_%s' % device_type)
59            setattr(cfm_helper.get_usb_devices, 'get_%s' % device_type,
60                    original_func)
61
62
63if __name__ == '__main__':
64    unittest.main()
65