summaryrefslogtreecommitdiffstats
path: root/unit-tests/unit
blob: 3b06c0407f8adb823433d7e90eca55af1772641d (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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#!/usr/bin/env python
#.awk '$0 ~ /case [0-9]+: .. 3/ { sys.stdout.write($2 }' src/dmidecode.c|tr ':\n' ', '

from pprint import pprint
import os, sys, subprocess, random, tempfile, time
if sys.version_info[0] < 3:
    import commands as subprocess
from getopt import getopt

# Setup temporary sys.path() with our build dir
(sysname, nodename, release, version, machine) = os.uname()
pyver = sys.version[:3]
sys.path.insert(0,'../build/lib.%s-%s-%s' % (sysname.lower(), machine, pyver))

root_user = (os.getuid() == 0 and True or False)

ERROR = False
HELP = False
VERBOSITY = 0
COLOR = False
DUMPS_D = "private"

try:
    opts, args = getopt(
        sys.argv[1:],
        "hcv",
        ["help", "color", "verbose"]
    )
    for o, a in opts:
        if o in ("-v", "--verbose"):
            VERBOSITY += 1
        elif o in ("-c", "--color"):
            COLOR = True
        elif o in ("-h", "--help"):
            HELP = True
except getopt.GetoptError as err:
    # print help information and exit:
    HELP = True
    ERROR = True

if HELP:
    sys.stdout.write("""
Usage: %s [<options>]

    OPTIONS

        [-h|--help]     #. Take a wild guess.
        [-c|--color]    #. Add pretty ANSI colors.
        [-v|--verbose]  #. The more you add, the louder it gets.

    NOTES

        Due to developer laziness, a single verbosity flag does nothing, so if
        you actually want to get some verbosity, add two verbosity flags (-vv)

""" % os.path.basename(sys.argv[0]))
    sys.exit(ERROR and 1 or 0)

def ascii(s, i):
        return (COLOR and "\033[%d;1m%s\033[0m" or "%d%s") % (30+i, str(s))
def black(s):
        return (COLOR and "\033[30;1m%s\033[0m" or "%s")%(str(s))
def red(s):
        return (COLOR and "\033[31;1m%s\033[0m" or "%s")%(str(s))
def green(s):
        return (COLOR and "\033[32;1m%s\033[0m" or "%s")%(str(s))
def yellow(s):
        return (COLOR and "\033[33;1m%s\033[0m" or "%s")%(str(s))
def blue(s):
        return (COLOR and "\033[34;1m%s\033[0m" or "%s")%(str(s))
def magenta(s):
        return (COLOR and "\033[35;1m%s\033[0m" or "%s")%(str(s))
def cyan(s):
        return (COLOR and "\033[36;1m%s\033[0m" or "%s")%(str(s))
def white(s):
        return (COLOR and "\033[37;1m%s\033[0m" or "%s")%(str(s))

DISPATCH = {
    1 : red,
    2 : green,
    3 : yellow,
    4 : blue,
    5 : magenta,
    6 : cyan,
    7 : white,
}

LINE = "%s\n"%(magenta("="*80))

score = {
    "total"   : 0,
    "skipped" : 0,
    "passed"  : 0,
    "warned"  : 0,
    "failed"  : 0,
}

def passed(msg=None, indent=1):
    global score
    score["total"] += 1
    score["passed"] += 1
    vwrite("%s\n"%green("PASS"), 1)
    if msg: vwrite("%s %s %s\n"%("  "*indent, green("P"), msg), 1)

def skipped(msg=None, indent=1):
    global score
    score["total"] += 1
    score["skipped"] += 1
    vwrite("%s\n"%yellow("SKIP"), 1)
    if msg: vwrite("%s %s %s\n"%("  "*indent, yellow("S"), msg), 1)

def warned(msg=None, indent=1):
    global score
    score["total"] += 1
    score["warned"] += 1
    vwrite("%s\n"%yellow("WARN"), 1)
    if msg: vwrite("%s %s %s\n"%("  "*indent, yellow("S"), msg), 1)

def failed(msg=None, indent=1):
    global score
    score["total"] += 1
    score["failed"] += 1
    vwrite("%s\n"%red("FAIL"), 1)
    if msg: vwrite("%s %s %s\n"%("  "*indent, red("F"), msg), 1)

def test(r, msg=None, indent=1, bad=failed):
    if r:
        passed(msg, indent)
        return True
    else:
        bad(msg, indent)
        return False

def vwrite(msg, vLevel=0):
    if vLevel < VERBOSITY:
        sys.stdout.write(msg)
        sys.stdout.flush()

################################################################################

#. Let's ignore warnings from the module for the test units...
err = open('/dev/null', 'a+', 1)
os.dup2(err.fileno(), sys.stderr.fileno())

vwrite(LINE, 1)
vwrite(" * Testing for command line version of dmidecode ...", 1)
dmidecode_bin = True in [
    os.path.exists(
        os.path.join(_, "dmidecode")
    ) for _ in os.getenv("PATH").split(':')
]
test(dmidecode_bin, bad=warned)
if root_user:
    vwrite(" * Running test as root user, all tests will be executed\n", 1)
else:
    vwrite(" * %s\n"%red("Running test as normal user, some tests will be skipped"), 1)

vwrite(" * Creation of temporary files...", 1)
try:
    FH, DUMP = tempfile.mkstemp()
    os.unlink(DUMP)
    os.close(FH)
    passed()
except:
    failed()

vwrite(LINE, 1)
try:
    vwrite(" * Importing module...", 1)
    import libxml2
    import dmidecode
    if not root_user:
        vwrite("\n%s"%cyan("Not running as root, a warning above can be expected..."), 1)
    passed()

    vwrite("   * Version: %s\n"%blue(dmidecode.version), 1)
    vwrite("   * DMI Version String: %s\n"%blue(dmidecode.dmi), 1)

    vwrite(" * Testing that default device is /dev/mem...", 1)
    test(dmidecode.get_dev() == "/dev/mem")

    if root_user:
        vwrite(" * Testing that write-lock will not break on dump()...", 1)
        test(not dmidecode.dump())

    vwrite(" * Testing ability to change device to %s..."%DUMP, 1)
    test(dmidecode.set_dev(DUMP))

    vwrite(" * Testing that device has changed to %s..."%DUMP, 1)
    test(dmidecode.get_dev() == DUMP)

    if root_user and dmidecode.dmi is not None:
        vwrite(" * Testing that write on new file is ok...", 1)
        test(dmidecode.dump())

        vwrite(" * Testing that file was actually written...", 1)
        time.sleep(0.1)
        if test(os.path.exists(DUMP)):
            os.unlink(DUMP)
    else:
        if dmidecode.dmi is None:
            vwrite(
                " * %s\n" % yellow(
                    "Skipped testing dump() function, dmidecode does not have access to DMI data"
                    ), 1)
        else:
            vwrite(
                " * %s\n" % red(
                    "Skip testing API function, missing root privileges: dmidecode.dump()"
                    ), 1)

    types = list(range(0, 42))+list(range(126, 128))
    bad_types = [-1, -1000, 256]
    sections = [
        "bios",
        "system",
        "baseboard",
        "chassis",
        "processor",
        "memory",
        "cache",
        "connector",
        "slot"
    ]
    devices = []
    if os.path.exists(DUMPS_D):
        devices.extend([os.path.join(DUMPS_D, _) for _ in os.listdir(DUMPS_D)])
    else:
        vwrite(" * If you have memory dumps to test, create a directory called `%s' and drop them in there.\n" % DUMPS_D, 1)

    if root_user and dmidecode.dmi is not None:
        devices.append("/dev/mem")
    else:
        if dmidecode.dmi is not None:
            vwrite(" * %s\n"%red("Running test as normal user, will not try to read /dev/mem"), 1)

    try:
        pymap = '../src/pymap.xml'
        vwrite(" * Loading %s for XML->Python dictonary mapping..." % pymap, 1)
        dmidecode.pythonmap(pymap)
        passed()
    except:
        failed()

    random.shuffle(types)
    random.shuffle(devices)
    random.shuffle(sections)

    for dev in devices:
        vwrite(LINE, 1)
        vwrite(" * Testing %s..."%yellow(dev), 1)
        try:
            fH = open(dev, 'r')
            fH.close()
            passed()
            vwrite("   * Testing set_dev/get_dev on %s..."%(yellow(dev)), 1)
            if test(dmidecode.set_dev(dev) and dmidecode.get_dev() == dev):
                i = 0
                for section in sections:
                    i += 1
                    vwrite("   * Testing %s (%d/%d)..."%(cyan(section), i, len(sections)), 1)
                    try:
                        output = getattr(dmidecode, section)()
                        test(output is not False)
                        if output:
                            vwrite("     * %s\n"%black(output.keys()), 1)
                    except LookupError as e:
                        failed(e, 1)

                for i in bad_types:
                    vwrite("   * Testing bad type %s..."%red(i), 1)
                    try:
                        output = dmidecode.type(i)
                        test(output is False)
                    except SystemError:
                        failed()

                for i in types:
                    vwrite("   * Testing type %s..."%red(i), 1)
                    try:
                        output = dmidecode.type(i)
                        if dmidecode_bin:
                            _output = subprocess.getoutput("dmidecode -t %d"%i).strip().split('\n')
                            test(len(_output) == 1 and len(output) == 0 or True)
                        else:
                            test(output is not False)
                        if output:
                            vwrite("     * %s\n"%output.keys(), 1)
                    except IOError as e:
                        failed(e, 1)
                    except LookupError as e:
                        failed(e, 1)


                dmixml = dmidecode.dmidecodeXML()
                try:
                    vwrite("   * XML: Swapping result type dmidecodeXML::SetResultType('-') - invalid type... ", 1)
                    test(not dmixml.SetResultType('-'))
                except TypeError:
                    vwrite("Not working => ", 1)
                    passed()
                except:
                    vwrite("Accepted => ", 1)
                    failed()

                try:
                    vwrite("   * XML: Swapping result type - dmidecodeXML::SetResultType(dmidecode.DMIXML_DOC) - valid type...", 1)
                    test(dmixml.SetResultType(dmidecode.DMIXML_DOC))
                    vwrite("   * XML: Swapping result type - dmidecodeXML::SetResultType(dmidecode.DMIXML_NODE) - valid type...", 1)
                    test(dmixml.SetResultType(dmidecode.DMIXML_NODE))
                except:
                    failed()

                for i in bad_types:
                    vwrite("   * XML: Testing bad type - dmidecodeXML::QueryTypeId(%s)..." % red(i), 1)
                    try:
                        output_node = dmixml.QueryTypeId(i)
                        test(not isinstance(output_node, libxml2.xmlNode))
                    except SystemError:
                        vwrite("Accepted => ", 1)
                        failed()
                    except TypeError:
                        vwrite("Not working => ", 1)
                        passed()
                    except ValueError:
                        vwrite("Not working => ", 1)
                        passed()

                for i in types:
                    vwrite("   * XML: Testing dmidecodeXML::QueryTypeId(%s)..." % red(i), 1)
                    try:
                        output_node = dmixml.QueryTypeId(i)
                        test(isinstance(output_node, libxml2.xmlNode))
                    except Exception as e:
                        failed(e, 1)
                    except:
                        failed()

                dmixml.SetResultType(dmidecode.DMIXML_DOC)
                i = 0
                for section in sections:
                    i += 1
                    vwrite("   * %s (%d/%d)..." % (
                        "XML: Testing dmidecodeXML::QuerySection('%s')" % cyan(
                            section
                        ), i, len(sections)
                    ), 1)
                    try:
                        output_doc = dmixml.QuerySection(section)
                        test(isinstance(output_doc, libxml2.xmlDoc))
                    except Exception as e:
                        failed(e, 1)
                    except:
                        failed()

        except IOError:
            skipped()

except ImportError as err:
    failed()
    print(err)

vwrite(LINE, 1)
vwrite("Devices : %s\n"%cyan(len(devices)), 1)
vwrite("Total   : %s\n"%blue(score["total"]), 1)
vwrite("Skipped : %s\n"%yellow(score["skipped"]), 1)
vwrite("Warned  : %s\n"%yellow(score["warned"]), 1)
vwrite("Passed  : %s\n"%green(score["passed"]), 1)
vwrite("Failed  : %s\n"%red(score["failed"]), 1)

sys.exit(score["failed"] != 0 and 1 or 0)