File: validation.py

package info (click to toggle)
virtinst 0.400.0-7
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 1,388 kB
  • ctags: 953
  • sloc: python: 7,475; xml: 848; sh: 25; makefile: 11
file content (234 lines) | stat: -rw-r--r-- 11,582 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free  Software Foundation; either version 2 of the License, or
# (at your option)  any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.

import virtinst
from virtinst import VirtualDisk
import unittest
import traceback
import os

# Template for adding arguments to test
#      { 'label'    : { 'VAR'       : { 'invalid' : [param],\
#                                       'valid'   : [param]},\
#                       '__init__'  : { 'invalid' : [{'initparam':val}],\
#                                       'valid'   : [{'initparam':val}]}\

args = { 'guest'    : { \
                        'name'      : { 'invalid' : ['123456789', 'im_invalid!', '', 0, 'verylongnameverylongnameverylongnameverylongnameveryvery'], \
                                        'valid'   : ['Valid_name.01'] }, \
                        'memory'    : { 'invalid' : [-1, 0, ''], \
                                        'valid'   : [200, 2000] }, \
                        'maxmemory' : { 'invalid' : [-1, 0, ''], \
                                        'valid'   : [200, 2000], }, \
                        'uuid'      : { 'invalid' : [ '', 0, '1234567812345678123456781234567x'], \
                                        'valid'   : ['12345678123456781234567812345678','12345678-1234-1234-ABCD-ABCDEF123456']}, \
                        'vcpus'     : { 'invalid' : [-1, 0, 1000, ''], \
                                        'valid'   : [ 1, 32 ] }, \
                        'graphics'  : { 'invalid' : ['', True, 'unknown', {},\
('', '', '', 0), ('','','', 'longerthan16chars'), ('','','','invalid!!ch@r'),\
                                                    {}], \
                                        'valid'   : [False, 'sdl', 'vnc', \
                                                    (True, 'sdl', '',\
                                                    'key_map-2'),\
                                                    {'enabled' : True, \
                                                     'type':'vnc', 'opts':5900}\
                                                    ]},\
                        'type'      : { 'invalid' : [], \
                                        'valid'   : ['sometype'] }, \
                        'cdrom'     : { 'invalid' : ['', 0, '/somepath'],\
                                        'valid'   : ['/dev/loop0']}\
                      },\
         'fvguest'  : { \
                        'os_type'   : { 'invalid' : ['notpresent',0,''],\
                                        'valid'   : ['other', 'windows',\
                                                     'unix', 'linux']}, \
                        'os_variant': { 'invalid' : ['', 0, 'invalid'], \
                                        'valid'   : ['rhel5', \
                                                     'sles10']}, \
                      },\
         'disk' :
            { '__init__' :

                { 'invalid' :
                    [{ 'path' : 0},
                     { 'path' : '/root' },
                     { 'path' : 'valid', 'size' : None },
                     { 'path' : "valid", 'size' : 'invalid' },
                     { 'path' : 'valid', 'size' : -1},
                     { 'path' : 'notblock', 'type' : VirtualDisk.TYPE_BLOCK},
                     { 'path' :'/dev/null', 'type' : VirtualDisk.TYPE_BLOCK},
                     { 'path' : None },
                     { 'path' : "noexist", 'size' : 900000, 'sparse' : False },
                    ],

                  'valid' :
                    [{ 'path' : '/dev/loop0' },
                     { 'path' : 'nonexist', 'size' : 1 },
                     { 'path' :'/dev/null'},
                     { 'path' : None, 'device' : VirtualDisk.DEVICE_CDROM},
                     { 'path' : None, 'device' : VirtualDisk.DEVICE_FLOPPY},
                    ]
                },
            },

         'installer' : { \
                        'boot'      : { 'invalid' : ['', 0, ('1element'),\
                                                     ['1el', '2el', '3el'],\
                                                     {'1element': '1val'},\
                                                     {'kernel' : 'a',\
                                                      'wronglabel' : 'b'}],\
                                        'valid'   : [('kern', 'init'),\
                                                     ['kern', 'init'],\
                                                     { 'kernel' : 'a',\
                                                       'initrd' : 'b'}]}, \
                        'extraargs' : { 'invalid' : [], \
                                        'valid'   : ['someargs']}, \
                             },\
         'distroinstaller' : { \
                        'location'  : { 'invalid' : ['nogood', \
                                                     'http:/nogood'],\
                                        'valid'   : ['/dev/null',\
                                                     'http://web',\
                                                     'ftp://ftp',\
                                                     'nfs:nfsserv']}\
                             },\
         'network'   : { \
                        '__init__'  : { 'invalid' : [{'macaddr':0}, \
                                                     {'macaddr':''},\
                                                     {'macaddr':'$%XD'}, \
                                                     {'type':'network'}, \
                                                    ],
                                        'valid'   : []}, \
                     },\
         'clonedesign' : {\
                        'original_guest' :{\
                                        'invalid' : ['', 0, 'invalid_name&',\
                                        '123456781234567812345678123456789'],\
                                        'valid'   : ['some.valid-name_9', \
                                        '12345678123456781234567812345678']},\
                        'clone_name': { 'invalid' : [0],
                                        'valid'   : ['some.valid-name_9']},
                        'clone_uuid': { 'invalid' : [0],
                                        'valid'   :
                                        ['12345678123456781234567812345678']},\
                        'clone_mac' : { 'invalid' : ['badformat'],
                                        'valid'   : ['AA:BB:CC:DD:EE:FF']},\
                        'clone_bs'  : { 'invalid' : [],
                                        'valid'   : ['valid']}}\
       }

class TestValidation(unittest.TestCase):


    guest = virtinst.Guest(hypervisorURI="test:///default", type="xen")

    def _testArgs(self, object, testclass, name):
        """@object Object to test parameters against
           @testclass Full class to test initialization against
           @name String name indexing args"""
        for paramname in args[name]:
            for val in args[name][paramname]['invalid']:

                try:
                    if paramname is '__init__':
                        testclass(*(), **val)                    
                    else:
                        setattr(object, paramname, val)
                    msg = "Expected TypeError or ValueError: None raised.\n"
                    msg += "For '%s' object, paramname '%s', val '%s':" % \
                        (name, paramname, val)
                    raise AssertionError, msg
                except AssertionError, e:
                    raise e
                except ValueError:
                    pass
                except Exception, e:
                    msg = "Unexpected exception raised: %s\n" % e
                    msg += "Original traceback was: \n%s\n" % \
                           traceback.format_exc()
                    msg += "For '%s' object, paramname '%s', val '%s':" % \
                        (name, paramname, val)
                    raise AssertionError, msg
                
            for val in args[name][paramname]['valid']:
                try:
                    # Skip NFS test as non-root
                    if name == "distroinstaller" and paramname == "location" and val[0:3] == "nfs" and os.geteuid() != 0:
                        continue
                    if paramname is '__init__':
                        testclass(*(), **val)                    
                    else:
                        setattr(object, paramname, val)
                except Exception, e:
                    msg = "Validation case failed, expected success.\n"
                    msg +="Exception received was: %s\n" % e
                    msg += "Original traceback was: \n%s\n" % \
                           traceback.format_exc()
                    msg += "For '%s' object, paramname '%s', val '%s':" % \
                        (name, paramname, val)
                    raise AssertionError, msg

    # Actual Tests

    def testGuestValidation(self):
        PVGuest = virtinst.ParaVirtGuest(hypervisorURI="test:///default",\
                                         type="xen")
        self._testArgs(PVGuest, virtinst.Guest, 'guest')

    def testDiskValidation(self):
        disk = VirtualDisk("/dev/loop0")
        self._testArgs(disk, VirtualDisk, 'disk')

    def testFVGuestValidation(self):
        FVGuest = virtinst.FullVirtGuest(hypervisorURI="test:///default",\
                                         type="xen")
        self._testArgs(FVGuest, virtinst.FullVirtGuest, 'fvguest')

    def testNetworkValidation(self):
        network = virtinst.VirtualNetworkInterface()
        self._testArgs(network, virtinst.VirtualNetworkInterface, 'network')

        # Test MAC Address collision
        hostmac = virtinst.util.get_host_network_devices()
        if len(hostmac) is not 0:
            hostmac = hostmac[0][4]

        for params in ({'macaddr' : hostmac},):
            network = virtinst.VirtualNetworkInterface(*(), **params)
            self.assertRaises(RuntimeError, network.setup, \
                              self.guest.conn)
        
        # Test dynamic MAC/Bridge success
        try:
            network = virtinst.VirtualNetworkInterface()
            network.setup(self.guest.conn)
        except Exception, e:
            raise AssertionError, \
                "Network setup with no params failed, expected success." + \
                " Exception was: %s: %s" % (str(e), "".join(traceback.format_exc()))

    def testDistroInstaller(self):
       dinstall = virtinst.DistroInstaller()
       self._testArgs(dinstall, virtinst.DistroInstaller, 'installer')
       self._testArgs(dinstall, virtinst.DistroInstaller, 'distroinstaller')

    def testCloneManager(self):
        cman = virtinst.CloneManager.CloneDesign(self.guest.conn)
        self._testArgs(cman, virtinst.CloneManager.CloneDesign, 'clonedesign')
    

if __name__ == "__main__":
    unittest.main()