1import os
2import pytest
3from contextlib import contextmanager
4from buildstream import _yaml
5from buildstream._exceptions import ErrorDomain, LoadErrorReason
6from tests.testutils.runcli import cli
7
8# Project directory
9DATA_DIR = os.path.dirname(os.path.realpath(__file__))
10
11
12# Context manager to override the reported value of `os.uname()`
13@contextmanager
14def override_uname_arch(name):
15    orig_uname = os.uname
16    orig_tuple = tuple(os.uname())
17    override_result = (orig_tuple[0], orig_tuple[1],
18                       orig_tuple[2], orig_tuple[3],
19                       name)
20
21    def override():
22        return override_result
23
24    os.uname = override
25    yield
26    os.uname = orig_uname
27
28
29@pytest.mark.datafiles(DATA_DIR)
30@pytest.mark.parametrize("uname,value,expected", [
31    # Test explicitly provided arches
32    ('arm', 'arm', 'Army'),
33    ('arm', 'aarch64', 'Aarchy'),
34
35    # Test automatically derived arches
36    ('arm', None, 'Army'),
37    ('aarch64', None, 'Aarchy'),
38
39    # Test that explicitly provided arches dont error out
40    # when the `uname` reported arch is not supported
41    ('i386', 'arm', 'Army'),
42    ('x86_64', 'aarch64', 'Aarchy'),
43])
44def test_conditional(cli, datafiles, uname, value, expected):
45    with override_uname_arch(uname):
46        project = os.path.join(datafiles.dirname, datafiles.basename, 'option-arch')
47
48        bst_args = []
49        if value is not None:
50            bst_args += ['--option', 'machine_arch', value]
51
52        bst_args += [
53            'show',
54            '--deps', 'none',
55            '--format', '%{vars}',
56            'element.bst'
57        ]
58        result = cli.run(project=project, silent=True, args=bst_args)
59        result.assert_success()
60
61        loaded = _yaml.load_data(result.output)
62        assert loaded['result'] == expected
63
64
65@pytest.mark.datafiles(DATA_DIR)
66def test_unsupported_arch(cli, datafiles):
67
68    with override_uname_arch("x86_64"):
69        project = os.path.join(datafiles.dirname, datafiles.basename, 'option-arch')
70        result = cli.run(project=project, silent=True, args=[
71            'show',
72            '--deps', 'none',
73            '--format', '%{vars}',
74            'element.bst'
75        ])
76
77        result.assert_main_error(ErrorDomain.LOAD, LoadErrorReason.INVALID_DATA)
78