aboutsummaryrefslogtreecommitdiff
path: root/test/py/tests/test_env.py
blob: 940279651da0fc13696ef615e2c159305f815a92 (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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2015 Stephen Warren
# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.

# Test operation of shell commands relating to environment variables.

import os
import os.path
from subprocess import call, check_call, CalledProcessError

import pytest
import u_boot_utils

# FIXME: This might be useful for other tests;
# perhaps refactor it into ConsoleBase or some other state object?
class StateTestEnv(object):
    """Container that represents the state of all U-Boot environment variables.
    This enables quick determination of existant/non-existant variable
    names.
    """

    def __init__(self, u_boot_console):
        """Initialize a new StateTestEnv object.

        Args:
            u_boot_console: A U-Boot console.

        Returns:
            Nothing.
        """

        self.u_boot_console = u_boot_console
        self.get_env()
        self.set_var = self.get_non_existent_var()

    def get_env(self):
        """Read all current environment variables from U-Boot.

        Args:
            None.

        Returns:
            Nothing.
        """

        if self.u_boot_console.config.buildconfig.get(
                'config_version_variable', 'n') == 'y':
            with self.u_boot_console.disable_check('main_signon'):
                response = self.u_boot_console.run_command('printenv')
        else:
            response = self.u_boot_console.run_command('printenv')
        self.env = {}
        for l in response.splitlines():
            if not '=' in l:
                continue
            (var, value) = l.split('=', 1)
            self.env[var] = value

    def get_existent_var(self):
        """Return the name of an environment variable that exists.

        Args:
            None.

        Returns:
            The name of an environment variable.
        """

        for var in self.env:
            return var

    def get_non_existent_var(self):
        """Return the name of an environment variable that does not exist.

        Args:
            None.

        Returns:
            The name of an environment variable.
        """

        n = 0
        while True:
            var = 'test_env_' + str(n)
            if var not in self.env:
                return var
            n += 1

ste = None
@pytest.fixture(scope='function')
def state_test_env(u_boot_console):
    """pytest fixture to provide a StateTestEnv object to tests."""

    global ste
    if not ste:
        ste = StateTestEnv(u_boot_console)
    return ste

def unset_var(state_test_env, var):
    """Unset an environment variable.

    This both executes a U-Boot shell command and updates a StateTestEnv
    object.

    Args:
        state_test_env: The StateTestEnv object to update.
        var: The variable name to unset.

    Returns:
        Nothing.
    """

    state_test_env.u_boot_console.run_command('setenv %s' % var)
    if var in state_test_env.env:
        del state_test_env.env[var]

def set_var(state_test_env, var, value):
    """Set an environment variable.

    This both executes a U-Boot shell command and updates a StateTestEnv
    object.

    Args:
        state_test_env: The StateTestEnv object to update.
        var: The variable name to set.
        value: The value to set the variable to.

    Returns:
        Nothing.
    """

    bc = state_test_env.u_boot_console.config.buildconfig
    if bc.get('config_hush_parser', None):
        quote = '"'
    else:
        quote = ''
        if ' ' in value:
            pytest.skip('Space in variable value on non-Hush shell')

    state_test_env.u_boot_console.run_command(
        'setenv %s %s%s%s' % (var, quote, value, quote))
    state_test_env.env[var] = value

def validate_empty(state_test_env, var):
    """Validate that a variable is not set, using U-Boot shell commands.

    Args:
        var: The variable name to test.

    Returns:
        Nothing.
    """

    response = state_test_env.u_boot_console.run_command('echo ${%s}' % var)
    assert response == ''

def validate_set(state_test_env, var, value):
    """Validate that a variable is set, using U-Boot shell commands.

    Args:
        var: The variable name to test.
        value: The value the variable is expected to have.

    Returns:
        Nothing.
    """

    # echo does not preserve leading, internal, or trailing whitespace in the
    # value. printenv does, and hence allows more complete testing.
    response = state_test_env.u_boot_console.run_command('printenv %s' % var)
    assert response == ('%s=%s' % (var, value))

def test_env_echo_exists(state_test_env):
    """Test echoing a variable that exists."""

    var = state_test_env.get_existent_var()
    value = state_test_env.env[var]
    validate_set(state_test_env, var, value)

@pytest.mark.buildconfigspec('cmd_echo')
def test_env_echo_non_existent(state_test_env):
    """Test echoing a variable that doesn't exist."""

    var = state_test_env.set_var
    validate_empty(state_test_env, var)

def test_env_printenv_non_existent(state_test_env):
    """Test printenv error message for non-existant variables."""

    var = state_test_env.set_var
    c = state_test_env.u_boot_console
    with c.disable_check('error_notification'):
        response = c.run_command('printenv %s' % var)
    assert(response == '## Error: "%s" not defined' % var)

@pytest.mark.buildconfigspec('cmd_echo')
def test_env_unset_non_existent(state_test_env):
    """Test unsetting a nonexistent variable."""

    var = state_test_env.get_non_existent_var()
    unset_var(state_test_env, var)
    validate_empty(state_test_env, var)

def test_env_set_non_existent(state_test_env):
    """Test set a non-existant variable."""

    var = state_test_env.set_var
    value = 'foo'
    set_var(state_test_env, var, value)
    validate_set(state_test_env, var, value)

def test_env_set_existing(state_test_env):
    """Test setting an existant variable."""

    var = state_test_env.set_var
    value = 'bar'
    set_var(state_test_env, var, value)
    validate_set(state_test_env, var, value)

@pytest.mark.buildconfigspec('cmd_echo')
def test_env_unset_existing(state_test_env):
    """Test unsetting a variable."""

    var = state_test_env.set_var
    unset_var(state_test_env, var)
    validate_empty(state_test_env, var)

def test_env_expansion_spaces(state_test_env):
    """Test expanding a variable that contains a space in its value."""

    var_space = None
    var_test = None
    try:
        var_space = state_test_env.get_non_existent_var()
        set_var(state_test_env, var_space, ' ')

        var_test = state_test_env.get_non_existent_var()
        value = ' 1${%(var_space)s}${%(var_space)s} 2 ' % locals()
        set_var(state_test_env, var_test, value)
        value = ' 1   2 '
        validate_set(state_test_env, var_test, value)
    finally:
        if var_space:
            unset_var(state_test_env, var_space)
        if var_test:
            unset_var(state_test_env, var_test)

@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_checksum_no_size(state_test_env):
    """Test that omitted ('-') size parameter with checksum validation fails the
       env import function.
    """
    c = state_test_env.u_boot_console
    ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
    addr = '%08x' % ram_base

    with c.disable_check('error_notification'):
        response = c.run_command('env import -c %s -' % addr)
    assert(response == '## Error: external checksum format must pass size')

@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist_checksum_no_size(state_test_env):
    """Test that omitted ('-') size parameter with checksum validation fails the
       env import function when variables are passed as parameters.
    """
    c = state_test_env.u_boot_console
    ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
    addr = '%08x' % ram_base

    with c.disable_check('error_notification'):
        response = c.run_command('env import -c %s - foo1 foo2 foo4' % addr)
    assert(response == '## Error: external checksum format must pass size')

@pytest.mark.buildconfigspec('cmd_exportenv')
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist(state_test_env):
    """Test importing only a handful of env variables from an environment."""
    c = state_test_env.u_boot_console
    ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
    addr = '%08x' % ram_base

    set_var(state_test_env, 'foo1', 'bar1')
    set_var(state_test_env, 'foo2', 'bar2')
    set_var(state_test_env, 'foo3', 'bar3')

    c.run_command('env export %s' % addr)

    unset_var(state_test_env, 'foo1')
    set_var(state_test_env, 'foo2', 'test2')
    set_var(state_test_env, 'foo4', 'bar4')

    # no foo1 in current env, foo2 overridden, foo3 should be of the value
    # before exporting and foo4 should be of the value before importing.
    c.run_command('env import %s - foo1 foo2 foo4' % addr)

    validate_set(state_test_env, 'foo1', 'bar1')
    validate_set(state_test_env, 'foo2', 'bar2')
    validate_set(state_test_env, 'foo3', 'bar3')
    validate_set(state_test_env, 'foo4', 'bar4')

    # Cleanup test environment
    unset_var(state_test_env, 'foo1')
    unset_var(state_test_env, 'foo2')
    unset_var(state_test_env, 'foo3')
    unset_var(state_test_env, 'foo4')

@pytest.mark.buildconfigspec('cmd_exportenv')
@pytest.mark.buildconfigspec('cmd_importenv')
def test_env_import_whitelist_delete(state_test_env):

    """Test importing only a handful of env variables from an environment, with.
       deletion if a var A that is passed to env import is not in the
       environment to be imported.
    """
    c = state_test_env.u_boot_console
    ram_base = u_boot_utils.find_ram_base(state_test_env.u_boot_console)
    addr = '%08x' % ram_base

    set_var(state_test_env, 'foo1', 'bar1')
    set_var(state_test_env, 'foo2', 'bar2')
    set_var(state_test_env, 'foo3', 'bar3')

    c.run_command('env export %s' % addr)

    unset_var(state_test_env, 'foo1')
    set_var(state_test_env, 'foo2', 'test2')
    set_var(state_test_env, 'foo4', 'bar4')

    # no foo1 in current env, foo2 overridden, foo3 should be of the value
    # before exporting and foo4 should be empty.
    c.run_command('env import -d %s - foo1 foo2 foo4' % addr)

    validate_set(state_test_env, 'foo1', 'bar1')
    validate_set(state_test_env, 'foo2', 'bar2')
    validate_set(state_test_env, 'foo3', 'bar3')
    validate_empty(state_test_env, 'foo4')

    # Cleanup test environment
    unset_var(state_test_env, 'foo1')
    unset_var(state_test_env, 'foo2')
    unset_var(state_test_env, 'foo3')
    unset_var(state_test_env, 'foo4')

@pytest.mark.buildconfigspec('cmd_nvedit_info')
def test_env_info(state_test_env):

    """Test 'env info' command with all possible options.
    """
    c = state_test_env.u_boot_console

    response = c.run_command('env info')
    nb_line = 0
    for l in response.split('\n'):
        if 'env_valid = ' in l:
            assert '= invalid' in l or '= valid' in l or '= redundant' in l
            nb_line += 1
        elif 'env_ready =' in l or 'env_use_default =' in l:
            assert '= true' in l or '= false' in l
            nb_line += 1
        else:
            assert true
    assert nb_line == 3

    response = c.run_command('env info -p -d')
    assert 'Default environment is used' in response or "Environment was loaded from persistent storage" in response
    assert 'Environment can be persisted' in response or "Environment cannot be persisted" in response

    response = c.run_command('env info -p -d -q')
    assert response == ""

    response = c.run_command('env info -p -q')
    assert response == ""

    response = c.run_command('env info -d -q')
    assert response == ""

@pytest.mark.boardspec('sandbox')
@pytest.mark.buildconfigspec('cmd_nvedit_info')
@pytest.mark.buildconfigspec('cmd_echo')
def test_env_info_sandbox(state_test_env):
    """Test 'env info' command result with several options on sandbox
       with a known ENV configuration: ready & default & persistent
    """
    c = state_test_env.u_boot_console

    response = c.run_command('env info')
    assert 'env_ready = true' in response
    assert 'env_use_default = true' in response

    response = c.run_command('env info -p -d')
    assert 'Default environment is used' in response
    assert 'Environment cannot be persisted' in response

    response = c.run_command('env info -d -q')
    response = c.run_command('echo $?')
    assert response == "0"

    response = c.run_command('env info -p -q')
    response = c.run_command('echo $?')
    assert response == "1"

    response = c.run_command('env info -d -p -q')
    response = c.run_command('echo $?')
    assert response == "1"

def mk_env_ext4(state_test_env):

    """Create a empty ext4 file system volume."""
    c = state_test_env.u_boot_console
    filename = 'env.ext4.img'
    persistent = c.config.persistent_data_dir + '/' + filename
    fs_img = c.config.result_dir  + '/' + filename

    if os.path.exists(persistent):
        c.log.action('Disk image file ' + persistent + ' already exists')
    else:
        try:
            u_boot_utils.run_and_log(c, 'dd if=/dev/zero of=%s bs=1M count=16' % persistent)
            u_boot_utils.run_and_log(c, 'mkfs.ext4 %s' % persistent)
            sb_content = u_boot_utils.run_and_log(c, 'tune2fs -l %s' % persistent)
            if 'metadata_csum' in sb_content:
                u_boot_utils.run_and_log(c, 'tune2fs -O ^metadata_csum %s' % persistent)
        except CalledProcessError:
            call('rm -f %s' % persistent, shell=True)
            raise

    u_boot_utils.run_and_log(c, ['cp',  '-f', persistent, fs_img])
    return fs_img

@pytest.mark.boardspec('sandbox')
@pytest.mark.buildconfigspec('cmd_echo')
@pytest.mark.buildconfigspec('cmd_nvedit_info')
@pytest.mark.buildconfigspec('cmd_nvedit_load')
@pytest.mark.buildconfigspec('cmd_nvedit_select')
@pytest.mark.buildconfigspec('env_is_in_ext4')
def test_env_ext4(state_test_env):

    """Test ENV in EXT4 on sandbox."""
    c = state_test_env.u_boot_console
    fs_img = ''
    try:
        fs_img = mk_env_ext4(state_test_env)

        c.run_command('host bind 0  %s' % fs_img)

        response = c.run_command('ext4ls host 0:0')
        assert 'uboot.env' not in response

        # force env location: EXT4 (prio 1 in sandbox)
        response = c.run_command('env select EXT4')
        assert 'Select Environment on EXT4: OK' in response

        response = c.run_command('env save')
        assert 'Saving Environment to EXT4' in response

        response = c.run_command('env load')
        assert 'Loading Environment from EXT4... OK' in response

        response = c.run_command('ext4ls host 0:0')
        assert '8192 uboot.env' in response

        response = c.run_command('env info')
        assert 'env_valid = valid' in response
        assert 'env_ready = true' in response
        assert 'env_use_default = false' in response

        response = c.run_command('env info -p -d')
        assert 'Environment was loaded from persistent storage' in response
        assert 'Environment can be persisted' in response

        response = c.run_command('env info -d -q')
        assert response == ""
        response = c.run_command('echo $?')
        assert response == "1"

        response = c.run_command('env info -p -q')
        assert response == ""
        response = c.run_command('echo $?')
        assert response == "0"

        response = c.run_command('env erase')
        assert 'OK' in response

        response = c.run_command('env load')
        assert 'Loading Environment from EXT4... ' in response
        assert 'bad CRC, using default environment' in response

        response = c.run_command('env info')
        assert 'env_valid = invalid' in response
        assert 'env_ready = true' in response
        assert 'env_use_default = true' in response

        response = c.run_command('env info -p -d')
        assert 'Default environment is used' in response
        assert 'Environment can be persisted' in response

        # restore env location: NOWHERE (prio 0 in sandbox)
        response = c.run_command('env select nowhere')
        assert 'Select Environment on nowhere: OK' in response

        response = c.run_command('env load')
        assert 'Loading Environment from nowhere... OK' in response

        response = c.run_command('env info')
        assert 'env_valid = invalid' in response
        assert 'env_ready = true' in response
        assert 'env_use_default = true' in response

        response = c.run_command('env info -p -d')
        assert 'Default environment is used' in response
        assert 'Environment cannot be persisted' in response

    finally:
        if fs_img:
            call('rm -f %s' % fs_img, shell=True)