• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python2
2#
3# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Unit tests for server/cros/dynamic_suite/tools.py."""
8
9from __future__ import absolute_import
10from __future__ import division
11from __future__ import print_function
12
13import mox
14import six
15import unittest
16
17import common
18
19from autotest_lib.server.cros.dynamic_suite.fakes import FakeHost
20from autotest_lib.server.cros.dynamic_suite.host_spec import HostSpec
21from autotest_lib.server.cros.dynamic_suite import host_spec
22from autotest_lib.server.cros.dynamic_suite import tools
23from autotest_lib.server import frontend
24
25
26class DynamicSuiteToolsTest(mox.MoxTestBase):
27    """Unit tests for dynamic_suite tools module methods.
28
29    @var _BOARD: fake board to reimage
30    """
31
32    _BOARD = 'board'
33    _DEPENDENCIES = {'test1': ['label1'], 'test2': ['label2']}
34    _POOL = 'bvt'
35
36    def setUp(self):
37        super(DynamicSuiteToolsTest, self).setUp()
38        self.afe = self.mox.CreateMock(frontend.AFE)
39        self.tko = self.mox.CreateMock(frontend.TKO)
40        # Having these ordered by complexity is important!
41        host_spec_list = [HostSpec([self._BOARD, self._POOL])]
42        for dep_list in six.itervalues(self._DEPENDENCIES):
43            host_spec_list.append(
44                HostSpec([self._BOARD, self._POOL], dep_list))
45        self.specs = host_spec.order_by_complexity(host_spec_list)
46
47    def testInjectVars(self):
48        """Should inject dict of varibles into provided strings."""
49        def find_all_in(d, s):
50            """Returns true if all key-value pairs in |d| are printed in |s|
51            and the dictionary representation is also in |s|.
52
53            @param d: the variable dictionary to check.
54            @param s: the control file string.
55            """
56            for k, v in six.iteritems(d):
57                if isinstance(v, str):
58                    if "%s='%s'\n" % (k, v) not in s:
59                        return False
60                else:
61                    if "%s=%r\n" % (k, v) not in s:
62                        return False
63            args_dict_str = "%s=%s\n" % ('args_dict', repr(d))
64            if args_dict_str not in s:
65                return False
66            return True
67
68        v = {'v1': 'one', 'v2': 'two', 'v3': None, 'v4': False, 'v5': 5}
69        self.assertTrue(find_all_in(v, tools.inject_vars(v, '')))
70        self.assertTrue(find_all_in(v, tools.inject_vars(v, 'ctrl')))
71        control_file = tools.inject_vars(v, 'sample')
72        self.assertTrue(tools._INJECT_BEGIN in control_file)
73        self.assertTrue(tools._INJECT_END in control_file)
74
75    def testRemoveInjection(self):
76        """Tests remove the injected variables from control file."""
77        control_file = """
78# INJECT_BEGIN - DO NOT DELETE THIS LINE
79v1='one'
80v4=False
81v5=5
82args_dict={'v1': 'one', 'v2': 'two', 'v3': None, 'v4': False, 'v5': 5}
83# INJECT_END - DO NOT DELETE LINE
84def init():
85    pass
86        """
87        control_file = tools.remove_injection(control_file)
88        self.assertTrue(control_file.strip().startswith('def init():'))
89
90    def testRemoveLegacyInjection(self):
91        """Tests remove the injected variables from legacy control file."""
92        control_file = """
93v1='one'
94_v2=False
95v3_x11_=5
96args_dict={'v1': 'one', '_v2': False, 'v3_x11': 5}
97def init():
98    pass
99        """
100        control_file = tools.remove_legacy_injection(control_file)
101        self.assertTrue(control_file.strip().startswith('def init():'))
102        control_file = tools.remove_injection(control_file)
103        self.assertTrue(control_file.strip().startswith('def init():'))
104
105
106    def testIncorrectlyLocked(self):
107        """Should detect hosts locked by random users."""
108        host = FakeHost(locked=True, locked_by='some guy')
109        self.assertTrue(tools.incorrectly_locked(host))
110
111
112    def testNotIncorrectlyLocked(self):
113        """Should accept hosts locked by the infrastructure."""
114        infra_user = 'an infra user'
115        self.mox.StubOutWithMock(tools, 'infrastructure_user')
116        tools.infrastructure_user().AndReturn(infra_user)
117        self.mox.ReplayAll()
118        host = FakeHost(locked=True, locked_by=infra_user)
119        self.assertFalse(tools.incorrectly_locked(host))
120
121
122if __name__ == "__main__":
123    unittest.main()
124