Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / db / tests.py @ 8c7c9813

History | View | Annotate | Download (10.6 kB)

1
# Copyright 2012 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or without
4
# modification, are permitted provided that the following conditions
5
# are met:
6
#
7
#   1. Redistributions of source code must retain the above copyright
8
#      notice, this list of conditions and the following disclaimer.
9
#
10
#  2. Redistributions in binary form must reproduce the above copyright
11
#     notice, this list of conditions and the following disclaimer in the
12
#     documentation and/or other materials provided with the distribution.
13
#
14
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
15
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
18
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24
# SUCH DAMAGE.
25
#
26
# The views and conclusions contained in the software and documentation are
27
# those of the authors and should not be interpreted as representing official
28
# policies, either expressed or implied, of GRNET S.A.
29

    
30
# Unit Tests for db
31
#
32
# Provides automated tests for db module
33

    
34
from django.test import TestCase
35

    
36
from django.conf import settings
37
# Import pool tests
38
from synnefo.db.pools.tests import *
39

    
40
from synnefo.db.models import *
41
from synnefo.db import models_factory as mfact
42
from synnefo.db.pools import IPPool, EmptyPool
43

    
44
from django.db import IntegrityError
45
from django.core.exceptions import MultipleObjectsReturned
46
from snf_django.utils.testing import override_settings
47
from mock import patch
48

    
49

    
50
class FlavorTest(TestCase):
51
    def test_flavor_name(self):
52
        """Test a flavor object name method."""
53
        flavor = mfact.FlavorFactory(cpu=1, ram=1024, disk=40,
54
                                     disk_template="temp")
55
        self.assertEqual(flavor.name, "C1R1024D40temp", "flavor.name is not"
56
                " generated correctly. Name is %s instead of C1R1024D40temp" %
57
                flavor.name)
58

    
59

    
60
class BackendTest(TestCase):
61
    def setUp(self):
62
        self.backend = mfact.BackendFactory()
63

    
64
    @patch("synnefo.db.models.get_rapi_client")
65
    def test_get_client(self, client):
66
        id_ = self.backend.id
67
        hash_ = self.backend.hash
68
        name = self.backend.clustername
69
        passwd = self.backend.password
70
        user = self.backend.username
71
        port = self.backend.port
72
        self.backend.get_client()
73
        client.assert_called_once_with(id_, hash_, name, port, user, passwd)
74

    
75
    def test_save_hash(self):
76
        """Test that backend hash is generated on credential change"""
77
        old_hash = self.backend.hash
78
        for field in ['clustername', 'username', 'password', 'port']:
79
            value = 5181 if field == 'port' else 'foo'
80
            self.backend.__setattr__(field, value)
81
            self.backend.save()
82
            self.assertNotEqual(old_hash, self.backend.hash)
83
            old_hash = self.backend.hash
84

    
85
    def test_unique_index(self):
86
        """Test that each backend gets a unique index"""
87
        backends = [self.backend]
88
        for i in xrange(0, 14):
89
            backends.append(mfact.BackendFactory())
90
        indexes = map(lambda x: x.index, backends)
91
        self.assertEqual(len(indexes), len(set(indexes)))
92

    
93
    def test_backend_number(self):
94
        """Test that no more than 16 backends are created"""
95
        for i in xrange(0, 14):
96
            mfact.BackendFactory()
97
        self.assertRaises(Exception, mfact.BackendFactory, ())
98

    
99
    def test_delete_active_backend(self):
100
        """Test that a backend with non-deleted VMS is not deleted"""
101
        backend = mfact.BackendFactory()
102
        vm = mfact.VirtualMachineFactory(backend=backend)
103
        self.assertRaises(IntegrityError, backend.delete, ())
104
        vm.backend = None
105
        vm.save()
106
        backend.delete()
107

    
108
    def test_password_encryption(self):
109
        password_hash = self.backend.password
110
        self.backend.password = '123'
111
        self.assertNotEqual(self.backend.password_hash, '123')
112
        self.assertNotEqual(self.backend.password_hash, password_hash)
113
        self.assertEqual(self.backend.password, '123')
114

    
115
    def test_hypervisor(self):
116
        from synnefo.db.models import snf_settings
117
        kvm_backend = mfact.BackendFactory(hypervisor="kvm")
118
        xen_pvm_backend = mfact.BackendFactory(hypervisor="xen-pvm")
119
        xen_hvm_backend = mfact.BackendFactory(hypervisor="xen-hvm")
120
        with override_settings(snf_settings, GANETI_USE_HOTPLUG=True):
121
            self.assertTrue(kvm_backend.use_hotplug())
122
            self.assertFalse(xen_pvm_backend.use_hotplug())
123
            self.assertFalse(xen_hvm_backend.use_hotplug())
124
        with override_settings(snf_settings, GANETI_USE_HOTPLUG=False):
125
            self.assertFalse(kvm_backend.use_hotplug())
126
            self.assertFalse(xen_pvm_backend.use_hotplug())
127
            self.assertFalse(xen_hvm_backend.use_hotplug())
128
        kwargs = {"os": "snf-image+default",
129
                  "hvparams": {"kvm": {"foo1": "mpaz1"},
130
                               "xen-pvm": {"foo2": "mpaz2"},
131
                               "xen-hvm": {"foo3": "mpaz3"}}}
132
        with override_settings(snf_settings,
133
                               GANETI_CREATEINSTANCE_KWARGS=kwargs):
134
            self.assertEqual(kvm_backend.get_create_params(),
135
                             {"os": "snf-image+default",
136
                              "hvparams": {"foo1": "mpaz1"}})
137
            self.assertEqual(xen_pvm_backend.get_create_params(),
138
                             {"os": "snf-image+default",
139
                              "hvparams": {"foo2": "mpaz2"}})
140
            self.assertEqual(xen_hvm_backend.get_create_params(),
141
                             {"os": "snf-image+default",
142
                              "hvparams": {"foo3": "mpaz3"}})
143
        with override_settings(snf_settings, GANETI_CREATEINSTANCE_KWARGS={}):
144
            self.assertEqual(kvm_backend.get_create_params(), {"hvparams": {}})
145

    
146

    
147
class VirtualMachineTest(TestCase):
148
    def setUp(self):
149
        self.vm = mfact.VirtualMachineFactory()
150

    
151
    @patch("synnefo.db.models.get_rapi_client")
152
    def test_get_client(self, client):
153
        backend = self.vm.backend
154
        id_ = backend.id
155
        hash_ = backend.hash
156
        name = backend.clustername
157
        passwd = backend.password
158
        user = backend.username
159
        port = backend.port
160
        self.vm.get_client()
161
        client.assert_called_once_with(id_, hash_, name, port, user, passwd)
162

    
163
    def test_create(self):
164
        vm = VirtualMachine()
165
        self.assertEqual(vm.action, None)
166
        self.assertEqual(vm.backendjobid, None)
167
        self.assertEqual(vm.backendjobstatus, None)
168
        self.assertEqual(vm.backendopcode, None)
169
        self.assertEqual(vm.backendlogmsg, None)
170
        self.assertEqual(vm.operstate, 'BUILD')
171

    
172

    
173
class NetworkTest(TestCase):
174
    def setUp(self):
175
        self.net = mfact.NetworkWithSubnetFactory()
176

    
177
    def test_tags(self):
178
        net1 = mfact.NetworkFactory(flavor='IP_LESS_ROUTED')
179
        self.assertEqual(net1.backend_tag, ['ip-less-routed'])
180
        net1 = mfact.NetworkFactory(flavor='CUSTOM')
181
        self.assertEqual(net1.backend_tag, [])
182

    
183
    def test_create_backend_network(self):
184
        len_backends = len(Backend.objects.all())
185
        back = mfact.BackendFactory()
186
        self.net.create_backend_network(backend=back)
187
        BackendNetwork.objects.get(network=self.net, backend=back)
188
        back1 = mfact.BackendFactory()
189
        back2 = mfact.BackendFactory()
190
        self.net.create_backend_network()
191
        BackendNetwork.objects.get(network=self.net, backend=back1)
192
        BackendNetwork.objects.get(network=self.net, backend=back2)
193
        self.assertEqual(len(BackendNetwork.objects.filter(network=self.net)),
194
                         len_backends + 3)
195

    
196
    def test_pool(self):
197
        pool = self.net.get_pool()
198
        pool.network = self.net
199
        self.assertTrue(isinstance(pool, IPPool))
200

    
201
    def test_reserve_ip(self):
202
        net1 = mfact.NetworkWithSubnetFactory(subnet__cidr='192.168.2.0/24')
203
        net1.reserve_address('192.168.2.12')
204
        pool = net1.get_pool()
205
        self.assertFalse(pool.is_available('192.168.2.12'))
206
        net1.release_address('192.168.2.12')
207
        pool = net1.get_pool()
208
        self.assertTrue(pool.is_available('192.168.2.12'))
209

    
210

    
211
class BackendNetworkTest(TestCase):
212
    def test_mac_prefix(self):
213
        network = mfact.NetworkFactory(mac_prefix='aa:bb:c')
214
        backend = mfact.BackendFactory()
215
        bnet = mfact.BackendNetworkFactory(network=network, backend=backend)
216
        self.assertTrue(backend.index < 10)
217
        self.assertEqual(bnet.mac_prefix, 'aa:bb:c%s' % backend.index)
218

    
219
    def test_invalid_mac(self):
220
        network = mfact.NetworkFactory(mac_prefix='zz:bb:c')
221
        backend = mfact.BackendFactory()
222
        self.assertRaises(utils.InvalidMacAddress,
223
                          mfact.BackendNetworkFactory,
224
                          network=network, backend=backend)
225

    
226

    
227
class BridgePoolTest(TestCase):
228
    def test_no_pool(self):
229
        self.assertRaises(EmptyPool,
230
                          BridgePoolTable.get_pool)
231

    
232
    def test_two_pools(self):
233
        mfact.BridgePoolTableFactory()
234
        mfact.BridgePoolTableFactory()
235
        self.assertRaises(MultipleObjectsReturned, BridgePoolTable.get_pool)
236

    
237

    
238
class AESTest(TestCase):
239
    def test_encrypt_decrtypt(self):
240
        from synnefo.db import aes_encrypt as aes
241
        old = 'bar'
242
        new = aes.decrypt_db_charfield(aes.encrypt_db_charfield(old))
243
        self.assertEqual(old, new)
244

    
245
    def test_password_change(self):
246
        from synnefo.db import aes_encrypt as aes
247
        old_pass = aes.SECRET_ENCRYPTION_KEY
248
        old = 'bar'
249
        encrypted = aes.encrypt_db_charfield(old)
250
        aes.SECRET_ENCRYPTION_KEY = 'foo2'
251
        self.assertRaises(aes.CorruptedPassword, aes.decrypt_db_charfield,
252
                          encrypted)
253
        aes.SECRET_ENCRYPTION_KEY = old_pass
254
        new = aes.decrypt_db_charfield(encrypted)
255
        self.assertEqual(old, new)
256

    
257
    def test_big_secret(self):
258
        from synnefo.db import aes_encrypt as aes
259
        old = aes.SECRET_ENCRYPTION_KEY
260
        aes.SECRET_ENCRYPTION_KEY = \
261
            '91490231234814234812348913289481294812398421893489'
262
        self.assertRaises(ValueError, aes.encrypt_db_charfield, 'la')
263
        aes.SECRET_ENCRYPTION_KEY = old