1# SPDX-License-Identifier: Apache-2.0 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15from pathlib import Path 16 17import pytest 18from click.testing import CliRunner 19 20from imgtool.image import Image 21from imgtool.main import ( 22 comp_default_lp, 23 comp_default_dictsize, 24 comp_default_lc, 25 create_lzma2_header, 26 comp_default_pb, 27 imgtool, 28) 29 30VERSION = '2.0.0' 31HEADER_SIZE = 0x200 32SLOT_SIZE = 0x7a000 33 34 35@pytest.fixture 36def key_file() -> Path: 37 return Path(__file__).parents[2] / 'root-ec-p256.pem' 38 39 40def check_if_compressed(out_file: Path) -> bool: 41 # Verify output file. There should be better solution to check 42 # if the output file is correctly compressed with lzma2. 43 # For now we check only if the output image contains 44 # some specific for lzma2 values. 45 img = Image(version=VERSION, header_size=HEADER_SIZE, slot_size=SLOT_SIZE, pad_header=True) 46 img.load(out_file) 47 compression_header = create_lzma2_header( 48 dictsize=comp_default_dictsize, pb=comp_default_pb, 49 lc=comp_default_lc, lp=comp_default_lp 50 ) 51 return compression_header in img.payload 52 53 54@pytest.mark.parametrize( 55 'compression, compressed', 56 [ 57 ('lzma2', True), 58 ('disabled', False) 59 ] 60) 61def test_lzma2_compression(tmpdir: Path, key_file: Path, compression: str, compressed: bool): 62 """ 63 Test if lzma2 compression works by running ``imgtool sign`` 64 command and checking expected output. 65 """ 66 in_file = tmpdir / 'zephyr.bin' 67 with in_file.open("wb") as f: 68 f.write(b"hello world\x00\x00\x00\x00\x00" * 64) 69 out_file: Path = tmpdir / 'zephyr_signed.bin' 70 71 runner = CliRunner() 72 result = runner.invoke( 73 imgtool, 74 [ 75 'sign', 76 str(in_file), 77 str(out_file), 78 f'--header-size={HEADER_SIZE}', 79 f'--slot-size={SLOT_SIZE}', 80 f'--version={VERSION}', 81 '--pad-header', 82 f'--compression={compression}', 83 f'--key={key_file}' 84 ], 85 ) 86 assert result.exit_code == 0 87 assert out_file.exists() 88 assert check_if_compressed(out_file) is compressed 89