summaryrefslogtreecommitdiff
path: root/zephyr/zmake/tests/test_version.py
blob: 8881522e4b3d1ba1bde93e2f00b5948145c98d5d (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
# Copyright 2021 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for zmake version code."""

import datetime
import subprocess
import unittest.mock as mock

import pytest  # pylint: disable=import-error
import zmake.output_packers
import zmake.project
import zmake.version as version


# pylint:disable=redefined-outer-name,unused-argument


def _git_init(repo):
    """Create a new git repository."""
    repo.mkdir()
    subprocess.run(
        ["git", "-c", "init.defaultBranch=main", "-C", repo, "init"], check=True
    )


def _git_add(repo, path, contents="example!\n"):
    """Write contents and stage a file."""
    path.write_text(contents)
    subprocess.run(["git", "-C", repo, "add", path], check=True)


def _git_commit(repo, message="message!"):
    env = {
        "GIT_AUTHOR_NAME": "Alyssa P. Hacker",
        "GIT_AUTHOR_EMAIL": "aphacker@example.org",
        "GIT_AUTHOR_DATE": "Thu, 07 Apr 2005 22:13:13 +0200",
        "GIT_COMMITTER_NAME": "Ben Bitdiddle",
        "GIT_COMMITTER_EMAIL": "bitdiddle@example.org",
        "GIT_COMMITTER_DATE": "Tue, 30 Aug 2005 10:50:30 -0700",
    }
    subprocess.run(
        ["git", "-C", repo, "commit", "-m", message], check=True, env=env
    )


def _setup_example_repos(tmp_path):
    """Setup temporary project, zephyr base, and module repos.

    Args:
        tmp_path: Directory to set up files in.

    Returns:
        A 3-tuple of project, zephyr_base, modules_dict.
    """
    project_path = tmp_path / "prj"
    project_path.mkdir()

    project = zmake.project.Project(
        zmake.project.ProjectConfig(
            project_name="prj",
            zephyr_board="foo",
            output_packer=zmake.output_packers.RawBinPacker,
            supported_toolchains=["coreboot-sdk"],
            project_dir=project_path,
        ),
    )
    # Has one commit.
    zephyr_base = tmp_path / "zephyr_base"
    _git_init(zephyr_base)
    _git_add(
        zephyr_base,
        zephyr_base / "VERSION",
        "VERSION_MAJOR=2\nVERSION_MINOR=6\nPATCHLEVEL=99\n",
    )
    _git_commit(zephyr_base, "Added version file")

    # Has one commit.
    mod1 = tmp_path / "mod1"
    _git_init(mod1)
    _git_add(mod1, mod1 / "file1")
    _git_commit(mod1)

    # Has two commits.
    mod2 = tmp_path / "ec"
    _git_init(mod2)
    _git_add(mod2, mod2 / "file2")
    _git_commit(mod2)
    _git_add(mod2, mod2 / "file3")
    _git_commit(mod2)

    return project, zephyr_base, {"mod1": mod1, "ec": mod2}


def test_version_string(tmp_path):
    """Test a that version string is as expected."""
    project, zephyr_base, modules = _setup_example_repos(tmp_path)
    assert (
        version.get_version_string(
            project.config.project_name, zephyr_base, modules
        )
        == "prj_v2.6.4-ec:b5991f,os:377d26,mod1:02fd7a"
    )


def test_version_string_static(tmp_path):
    """Test a that version string with no git hashes."""
    project, zephyr_base, modules = _setup_example_repos(tmp_path)
    assert (
        version.get_version_string(
            project.config.project_name, zephyr_base, modules, static=True
        )
        == "prj_v2.6.0-STATIC"
    )


@pytest.fixture
def fake_user_hostname():
    """Fixture to provide a fake user and hostname."""
    with mock.patch("getpass.getuser", return_value="toukmond", autospec=True):
        with mock.patch("platform.node", return_value="pokey", autospec=True):
            yield


@pytest.fixture
def fake_date():
    """Fixture to provide a fake date."""
    fixed_date = datetime.datetime(2021, 6, 28, 3, 18, 53)
    with mock.patch("datetime.datetime") as mock_datetime:
        mock_datetime.now.return_value = fixed_date
        yield


HEADER_VERSION_STR = "trogdor_v2.6.1004-cmsis:0dead0,hal_stm32:0beef0,os:ad00da"
EXPECTED_HEADER = (
    "/* This file is automatically generated by zmake_tests */\n"
    '#define VERSION "trogdor_v2.6.1004-cmsis:0dead0,hal_stm32:0beef0,os:ad00da"\n'
    '#define CROS_EC_VERSION32 "trogdor_v2.6.1004-cmsis:0dead0,"\n'
    '#define BUILDER "toukmond@pokey"\n'
    '#define DATE "2021-06-28 03:18:53"\n'
    "#define CROS_FWID32 CROS_FWID_MISSING_STR\n"
)
HEADER_VERSION_STR_STATIC = "trogdor_v2.6.0-STATIC"
EXPECTED_HEADER_STATIC = (
    "/* This file is automatically generated by zmake_tests */\n"
    '#define VERSION "trogdor_v2.6.0-STATIC"\n'
    '#define CROS_EC_VERSION32 "trogdor_v2.6.0-STATIC"\n'
    '#define BUILDER "reproducible@build"\n'
    '#define DATE "STATIC_VERSION_DATE"\n'
    "#define CROS_FWID32 CROS_FWID_MISSING_STR\n"
)


def test_header_gen(fake_user_hostname, fake_date, tmp_path):
    """Test generating the version header."""
    # Test the simple case (static=False, no existing header).
    output_file = tmp_path / "ec_version.h"
    version.write_version_header(HEADER_VERSION_STR, output_file, "zmake_tests")
    assert output_file.read_text() == EXPECTED_HEADER


def test_header_gen_reproducible_build(tmp_path):
    """Test that reproducible builds produce the right header."""
    # With static=True this time.
    output_file = tmp_path / "ec_version.h"
    version.write_version_header(
        HEADER_VERSION_STR_STATIC, output_file, "zmake_tests", static=True
    )
    assert output_file.read_text() == EXPECTED_HEADER_STATIC


def test_header_gen_exists_not_changed(fake_user_hostname, fake_date, tmp_path):
    """Test that the version file is not changed."""
    # Test we don't overwrite if no changes needed.
    output_file = tmp_path / "ec_version.h"

    # First time, write and record mtime.
    version.write_version_header(HEADER_VERSION_STR, output_file, "zmake_tests")
    expected_mtime = output_file.stat().st_mtime

    # Do another write (contents should be unchanged).
    version.write_version_header(HEADER_VERSION_STR, output_file, "zmake_tests")

    # Assert we didn't write again.
    assert output_file.stat().st_mtime == expected_mtime


def test_header_gen_exists_needs_changes(
    fake_user_hostname, fake_date, tmp_path
):
    """Test that the version file is changed, when needed."""
    # Test we overwrite when it exists already and changes are needed.
    output_file = tmp_path / "ec_version.h"

    # First time, write and save contents.
    version.write_version_header(HEADER_VERSION_STR, output_file, "zmake_tests")
    original_contents = output_file.read_text()

    # Do another write (contents should be changed).
    version.write_version_header(
        HEADER_VERSION_STR_STATIC, output_file, "zmake_tests", static=True
    )

    # Assert we overwrote.
    assert output_file.read_text() != original_contents