# SPDX-License-Identifier: GPL-3.0-or-later
"""
Tests for miscellaneous utility methods.
"""

import pytest
from freedommaker import utils


def test_add_disk_offsets():
    """Test disk offset addition."""
    assert utils.add_disk_offsets('1MiB', '2MiB') == '3MiB'
    # mib is not allowed as unit. Only MiB.
    with pytest.raises(NotImplementedError):
        utils.add_disk_offsets('1mib', '1mib')

    with pytest.raises(NotImplementedError):
        utils.add_disk_offsets('1GiB', '1MiB')

    with pytest.raises(NotImplementedError):
        utils.add_disk_offsets('1MiB', '1GiB')

    with pytest.raises(ValueError):
        utils.add_disk_offsets('xMiB', '1MiB')

    with pytest.raises(ValueError):
        utils.add_disk_offsets('xMiB', 'xMiB')


def test_parse_disk_size():
    """Test parsing disk sizes."""
    assert utils.parse_disk_size(0) == 0
    assert utils.parse_disk_size(123) == 123
    assert utils.parse_disk_size('123') == 123
    assert utils.parse_disk_size('123b') == 123
    assert utils.parse_disk_size('123k') == 123 * 1024
    assert utils.parse_disk_size('123K') == 123 * 1024
    assert utils.parse_disk_size('123M') == 123 * 1024 * 1024
    assert utils.parse_disk_size('123G') == 123 * 1024 * 1024 * 1024
    assert utils.parse_disk_size('123T') == 123 * 1024 * 1024 * 1024 * 1024
    with pytest.raises(ValueError):
        utils.parse_disk_size('-1M')

    with pytest.raises(ValueError):
        utils.parse_disk_size('1B')

    with pytest.raises(ValueError):
        utils.parse_disk_size('1P')

    with pytest.raises(ValueError):
        utils.parse_disk_size('test')


def test_format_disk_size():
    """Test that formatting disk sizes works."""
    assert utils.format_disk_size(0) == '0'
    assert utils.format_disk_size(1) == '1'
    assert utils.format_disk_size(1023) == '1023'
    assert utils.format_disk_size(1024) == '1K'
    assert utils.format_disk_size(1023 * 1023) == '1046529'
    assert utils.format_disk_size(1023 * 1024) == '1023K'
    assert utils.format_disk_size(1024 * 1024) == '1M'
    assert utils.format_disk_size(1023 * 1024 * 1024) == '1023M'
    assert utils.format_disk_size(1024 * 1024 * 1024) == '1G'
    assert utils.format_disk_size(1023 * 1024 * 1024 * 1024) == '1023G'
    assert utils.format_disk_size(1024 * 1024 * 1024 * 1024) == '1T'
    assert utils.format_disk_size(1023 * 1024 * 1024 * 1024 * 1024) == '1023T'


def test_add_disk_sizes():
    """Test that adding two disk sizes works as expected."""
    assert utils.add_disk_sizes('1M', '1K') == '1025K'
    assert utils.add_disk_sizes('1G', '1K') == '1048577K'
    assert utils.add_disk_sizes('512M', '512M') == '1G'
    assert utils.add_disk_sizes('3800M', '1000M') == '4800M'
