import shutil
import sys

import pytest

from clarabot_nano.utility.java import get_java_version_output, parse_java_major_version

_JAVA_EXE = shutil.which("java.exe" if sys.platform.startswith("win") else "java")


@pytest.mark.skipif(not _JAVA_EXE, reason="no java found in PATH")
def test_get_java_version_output():
    output = get_java_version_output()
    assert output and output.find(" version ") >= 0, str(output)
    assert output == get_java_version_output(_JAVA_EXE)


def test_parse_java_major_version():
    for text, result in [
        ('java version "1.6.0"', 6),
        ('java version "1.7.0"', 7),
        ('openjdk version "1.8.0"', 8),
        ('\n java version "1.8.0_2"\n', 8),
        ('openjdk version "10.1.0"', 10),
        ('openjdk version "11.0.12"\nstuff\nxyz\n', 11),
        ('java version "17.0.8_21"', 17),
    ]:
        output = parse_java_major_version(text)
        assert output == result, f"{output} {result}\n{text}"
