summaryrefslogtreecommitdiffstats
path: root/src/software/test/test_software_identity_resource.py
blob: 6f642d177998b99a673ae0f7e7b0d9c227102ec7 (plain)
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#!/usr/bin/env python
#
# Copyright (C) 2012-2013 Red Hat, Inc.  All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# Authors: Michal Minar <miminar@redhat.com>
#
"""
Unit tests for LMI_SoftwareIdentityResource provider.
"""

from datetime import datetime
import os
import pywbem
import socket
import time
import unittest

from lmi.software.core.IdentityResource import Values
import base
import repository
import util

class TestSoftwareIdentityResource(
        base.SoftwareBaseTestCase): #pylint: disable=R0904
    """
    Basic cim operations test.
    """

    CLASS_NAME = "LMI_SoftwareIdentityResource"
    KEYS = ("CreationClassName", "Name", "SystemCreationClassName",
            "SystemName")

    @classmethod
    def needs_pkgdb(cls):
        return False

    @classmethod
    def needs_repodb(cls):
        return True

    def make_op(self, repo):
        """
        @param ses SoftwareElementState property value
        @return object path of SoftwareIdentityResource
        """
        if isinstance(repo, repository.Repository):
            repo = repo.repoid
        objpath = self.objpath.copy()
        objpath["Name"] = repo
        objpath["SystemName"] = socket.getfqdn()
        return objpath

    def tearDown(self):
        for repo in self.repodb:
            if repository.is_repo_enabled(repo) != repo.status:
                repository.set_repo_enabled(repo, repo.status)

    def _check_repo_instance(self, repo, inst):
        """
        Checks instance properties of repository.
        """
        objpath = self.make_op(repo)
        self.assertEqual(objpath, inst.path)
        for key in self.KEYS:
            self.assertEqual(inst[key], inst.path[key])
        self.assertEqual(repo.repoid, inst["Name"])
        self.assertIsInstance(inst["AccessContext"], pywbem.Uint16)

        access_info = inst["AccessInfo"]
        if access_info is not None and access_info.endswith('/'):
            access_info = access_info[:-1]
        if access_info is not None:
            self.assertIsInstance(access_info, basestring)
        if repo.mirror_list:
            self.assertEqual(access_info, repo.mirror_list,
                    "AccessInfo does not match mirror_list for repo %s" %
                    repo.repoid)
        elif repo.metalink:
            self.assertEqual(access_info, repo.metalink,
                    "AccessInfo does not match metalink for repo %s" %
                    repo.repoid)
        elif access_info is not None:
            self.assertIn(access_info, repo.base_urls,
                "AccessInfo missing in base_urls for repo %s" % repo.repoid)

        self.assertIsInstance(inst["AvailableRequestedStates"], list)
        self.assertEqual(repo.name, inst["Caption"])
        self.assertIsInstance(inst["Cost"], pywbem.Sint32)
        self.assertIsInstance(inst["Description"], basestring)
        self.assertEqual(repo.repoid, inst["ElementName"])
        self.assertEqual(5, inst["EnabledDefault"])
        self.assertEqual(2 if repo.status else 3, inst["EnabledState"],
                "EnabledState does not match for repo %s" % repo.repoid)
        self.assertEqual(3, inst["ExtendedResourceType"])
        if repo.revision is None:
            self.assertIsNone(inst["Generation"])
        else:
            self.assertEqual(repo.revision, inst["Generation"],
                    "Generation does not match for repo %s" % repo.repoid)
        if repo.status:
            self.assertEqual(5, inst["HealthState"])    # OK
            self.assertEqual([2], inst["OperationalStatus"])    # OK
            self.assertEqual(1, inst["PrimaryStatus"])  # OK
        else:
            # repo may not be enabled, but still it can be ready
            # (which is not documented), so let's check both posibilities
            self.assertIn(inst["HealthState"], [5, 20])     # OK, Major Failure
            self.assertIn(inst["OperationalStatus"], [[2], [6]])    # [OK], [Error]
            self.assertIn(inst["PrimaryStatus"], [1, 3])    # OK, Error
        self.assertIsInstance(inst["GPGCheck"], bool)
        self.assertEqual(200, inst["InfoFormat"])
        self.assertEqual("LMI:LMI_SoftwareIdentityResource:"+repo.repoid,
                inst["InstanceID"])
        if repo.mirror_list is None:
            self.assertIsNone(inst["MirrorList"])
        else:
            self.assertEqual(
                    repo.metalink if repo.metalink else repo.mirror_list,
                    inst["MirrorList"])
        self.assertIsInstance(inst["OtherAccessContext"], basestring)
        #self.assertEqual(repo.pkg_count, inst["PackageCount"],
                #"PackageCount does not match for repo %s" % repo.repoid)
        self.assertIsInstance(inst["RepoGPGCheck"], bool)
        self.assertEqual(2 if repo.status else 3, inst["RequestedState"])
        self.assertEqual(1, inst["ResourceType"])
        self.assertIsInstance(inst["StatusDescriptions"], list)
        self.assertEqual(1, len(inst["StatusDescriptions"]))
        if repo.last_updated is None:
            self.assertIsNone(inst["TimeOfLastUpdate"])
        else:
            time_stamp = repo.last_updated.replace(
                    microsecond=0, tzinfo=pywbem.cim_types.MinutesFromUTC(0))
            self.assertEqual(time_stamp, inst["TimeOfLastUpdate"].datetime)
        time_stamp = datetime.fromtimestamp(os.stat(repo.filename).st_mtime) \
            .replace( microsecond=0
                    , tzinfo=pywbem.cim_types.MinutesFromUTC(0))
        self.assertEqual(time_stamp, inst["TimeOfLastStateChange"].datetime)
        self.assertEqual(12, inst["TransitioningToState"])

    def test_get_instance_safe(self):
        """
        Tests GetInstance call.
        """
        for repo in self.repodb:
            objpath = self.make_op(repo)
            inst = self.conn.GetInstance(InstanceName=objpath)
            self._check_repo_instance(repo, inst)

    @base.mark_dangerous
    def test_get_instance(self):
        """
        Dangerous test, making sure, that properties are set correctly
        for enabled and disabled repositories.
        """
        for repo in self.repodb:
            objpath = self.make_op(repo)
            self.assertIs(repository.is_repo_enabled(repo), repo.status)
            inst = self.conn.GetInstance(InstanceName=objpath)
            self.assertEqual(objpath, inst.path)
            for key in self.KEYS:
                self.assertEqual(inst[key], inst.path[key])
            self.assertEqual(repo.repoid, inst["Name"])
            self.assertEqual(2 if repo.status else 3, inst["EnabledState"])
            self.assertEqual(2 if repo.status else 3, inst["RequestedState"])
        for repo in self.repodb:
            objpath = self.make_op(repo)
            time.sleep(1) # to make sure, that change will be noticed
            repository.set_repo_enabled(repo, not repo.status)
            self.assertIs(repository.is_repo_enabled(repo), not repo.status)
            inst = self.conn.GetInstance(InstanceName=objpath)
            self.assertEqual(repo.repoid, inst["Name"])
            self.assertEqual(3 if repo.status else 2, inst["EnabledState"])
            self.assertEqual(3 if repo.status else 2, inst["RequestedState"])

    def test_enum_instance_names(self):
        """
        Tests EnumInstanceNames call on all repositories.
        """
        inames = self.conn.EnumerateInstanceNames(ClassName=self.CLASS_NAME)
        self.assertEqual(len(inames), len(self.repodb))
        repoids = set(r.repoid for r in self.repodb)
        for iname in inames:
            self.assertIsInstance(iname, pywbem.CIMInstanceName)
            self.assertEqual(iname.namespace, 'root/cimv2')
            self.assertEqual(sorted(iname.keys()), sorted(self.KEYS))
            self.assertIn(iname["Name"], repoids)
            objpath = self.make_op(iname["Name"])
            self.assertEqual(objpath, iname)

    def test_enum_instances(self):
        """
        Tests EnumInstances call on all repositories.
        """
        insts = self.conn.EnumerateInstances(ClassName=self.CLASS_NAME)
        self.assertGreater(len(insts), 0)
        repoids = dict((r.repoid, r) for r in self.repodb)
        for inst in insts:
            self.assertIsInstance(inst, pywbem.CIMInstance)
            self.assertIn(inst["Name"], repoids)
            self._check_repo_instance(repoids[inst["Name"]], inst)

    @base.mark_dangerous
    def test_request_state_change(self):
        """
        Tests InvokeMethod on RequestStateChange().
        """
        for repo in self.repodb:
            objpath = self.make_op(repo)
            self.assertIs(repository.is_repo_enabled(repo), repo.status)

            # change state of repository (enabled/disabled)
            req_state = (  Values.RequestStateChange.RequestedState.Disabled
                        if repo.status else
                           Values.RequestStateChange.RequestedState.Enabled)
            (res, oparms) = self.conn.InvokeMethod(
                    MethodName="RequestStateChange",
                    ObjectName=objpath,
                    RequestedState=req_state)
            self.assertEqual(0, res) #Completed with no error
            self.assertEqual(0, len(oparms))
            inst = self.conn.GetInstance(InstanceName=objpath)
            self.assertEqual(inst["EnabledState"], req_state)
            for pkg in self.dangerous_pkgs:
                if pkg.up_repo == repo:
                    pkg_iname = util.make_identity_path(pkg)
                    self.assertRaisesCIM(pywbem.CIM_ERR_NOT_FOUND,
                        self.conn.GetInstance, pkg_iname)

            # revert back to original configuration
            req_state = (  Values.RequestStateChange.RequestedState.Enabled
                        if repo.status else
                           Values.RequestStateChange.RequestedState.Disabled)
            (res, oparms) = self.conn.InvokeMethod(
                    MethodName="RequestStateChange",
                    ObjectName=objpath,
                    RequestedState=req_state)
            self.assertEqual(0, res) #Completed with no error
            self.assertEqual(0, len(oparms))
            inst = self.conn.GetInstance(InstanceName=objpath)
            self.assertEqual(inst["EnabledState"], req_state)
            for pkg in self.dangerous_pkgs:
                if pkg.up_repo == repo:
                    pkg_iname = util.make_identity_path(pkg)
                    inst = self.conn.GetInstance(pkg_iname)
                    self.assertIsInstance(inst, pywbem.CIMInstance)

def suite():
    """For unittest loaders."""
    return unittest.TestLoader().loadTestsFromTestCase(
            TestSoftwareIdentityResource)

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