File: test_JDK__verify.py

package info (click to toggle)
python-briefcase 0.3.22-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,300 kB
  • sloc: python: 59,405; makefile: 57
file content (591 lines) | stat: -rw-r--r-- 19,701 bytes parent folder | download | duplicates (2)
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import os
import shutil
import subprocess
from pathlib import Path
from unittest.mock import MagicMock, call

import pytest

from briefcase.exceptions import (
    BriefcaseCommandError,
    IncompatibleToolError,
    MissingToolError,
    NetworkFailure,
    UnsupportedHostError,
)
from briefcase.integrations.java import JDK

from ...utils import assert_url_resolvable, create_zip_file
from .conftest import JDK_BUILD, JDK_RELEASE

CALL_JAVA_HOME = call(["/usr/libexec/java_home"], quiet=1)


def test_short_circuit(mock_tools):
    """Tool is not created if already cached."""
    mock_tools.java = "tool"

    tool = JDK.verify(mock_tools)

    assert tool == "tool"
    assert tool == mock_tools.java


def test_unsupported_os(mock_tools):
    """When host OS is not supported, an error is raised."""
    mock_tools.host_os = "wonky"

    with pytest.raises(
        UnsupportedHostError,
        match=f"{JDK.name} is not supported on wonky",
    ):
        JDK.verify(mock_tools)


def test_unsupported_arch(mock_tools):
    """When the architecture is not supported, an error is raised."""
    mock_tools.host_arch = "IA-64"

    with pytest.raises(
        IncompatibleToolError,
        match="Briefcase cannot install Java JDK on this machine.",
    ):
        JDK.verify(mock_tools)


def test_macos_tool_java_home(mock_tools, capsys):
    """On macOS, the /usr/libexec/java_home utility is checked."""
    # Mock being on macOS
    mock_tools.host_os = "Darwin"

    # Mock 2 calls to check_output.
    mock_tools.subprocess.check_output.side_effect = [
        "/path/to/java",
        f"javac {JDK_RELEASE}\n",
    ]

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JDK should have the path returned by the tool
    assert mock_tools.java.java_home == Path("/path/to/java")

    assert mock_tools.subprocess.check_output.mock_calls == [
        CALL_JAVA_HOME,
        # Second is a call to verify a valid Java version
        call([Path("/path/to/java/bin/javac"), "-version"]),
    ]

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


def test_macos_tool_failure(mock_tools, tmp_path, capsys):
    """On macOS, if the libexec tool fails, the Briefcase JDK is used."""
    # Mock being on macOS
    mock_tools.host_os = "Darwin"

    # Mock a failed call on the libexec tool
    mock_tools.subprocess.check_output.side_effect = subprocess.CalledProcessError(
        returncode=1, cmd="/usr/libexec/java_home"
    )

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / "tools/java17/Contents/Home/bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    jdk = JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert jdk.java_home == tmp_path / "tools/java17/Contents/Home"

    assert mock_tools.subprocess.check_output.mock_calls == [CALL_JAVA_HOME]

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


def test_macos_wrong_jdk_version(mock_tools, tmp_path, capsys):
    """On macOS, if the libexec tool returns an unqualified JDK, the Briefcase JDK is
    used."""
    # Mock being on macOS
    mock_tools.host_os = "Darwin"

    # Mock 2 calls to check_output.
    mock_tools.subprocess.check_output.side_effect = [
        "/path/to/java",
        "java 1.8.0_352\n",
    ]

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / "tools/java17/Contents/Home/bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    jdk = JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert jdk.java_home == tmp_path / "tools/java17/Contents/Home"

    assert mock_tools.subprocess.check_output.mock_calls == [
        CALL_JAVA_HOME,
        call([Path("/path/to/java/bin/javac"), "-version"]),
    ]

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


def test_macos_invalid_jdk_path(mock_tools, tmp_path, capsys):
    """On macOS, if the libexec tool points to non-JDK path, the Briefcase JDK is
    used."""
    # Mock being on macOS
    mock_tools.host_os = "Darwin"

    # Mock 2 calls to check_output.
    mock_tools.subprocess.check_output.side_effect = [
        "/path/to/java",
        IndexError,
    ]

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / "tools/java17/Contents/Home/bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    jdk = JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert jdk.java_home == tmp_path / "tools/java17/Contents/Home"

    assert mock_tools.subprocess.check_output.mock_calls == [
        CALL_JAVA_HOME,
        call([Path("/path/to/java/bin/javac"), "-version"]),
    ]

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


def test_macos_provided_overrides_tool_java_home(mock_tools, capsys):
    """On macOS, an explicit JAVA_HOME overrides /usr/libexec/java_home."""
    # Mock being on macOS
    mock_tools.host_os = "Darwin"

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/java"}

    # Mock return value from javac. libexec won't be invoked.
    mock_tools.subprocess.check_output.return_value = f"javac {JDK_RELEASE}\n"

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JDK should have the path returned by the tool
    assert mock_tools.java.java_home == Path("/path/to/java")

    # A single call to check output
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/java/bin/javac"), "-version"],
    ),

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


def test_valid_provided_java_home(mock_tools, capsys):
    """If a valid JAVA_HOME is provided, it is used."""

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/java"}

    # Mock return value from javac.
    mock_tools.subprocess.check_output.return_value = f"javac {JDK_RELEASE}\n"

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JDK should have the path returned by the tool
    assert mock_tools.java.java_home == Path("/path/to/java")

    # A single call to check output
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/java/bin/javac"), "-version"],
    ),

    # No console output
    output = capsys.readouterr()
    assert output.out == ""
    assert output.err == ""


@pytest.mark.parametrize(
    "host_os, java_home",
    [
        ("Linux", Path("tools", "java17")),
        ("Windows", Path("tools", "java17")),
        ("Darwin", Path("tools", "java17", "Contents", "Home")),
    ],
)
def test_invalid_jdk_version(mock_tools, host_os, java_home, tmp_path, capsys):
    """If the JDK pointed to by JAVA_HOME isn't a Java 8 JDK, the briefcase JDK is
    used."""
    # Mock os
    mock_tools.host_os = host_os

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/java"}

    # Mock return value from javac.
    mock_tools.subprocess.check_output.return_value = "javac 14\n"

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / java_home / "bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert mock_tools.java.java_home == tmp_path / java_home

    # A single call was made to check javac
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/java/bin/javac"), "-version"],
    )

    # Warning is shown for invalid JAVA_HOME
    output = capsys.readouterr()
    assert "WARNING: JAVA_HOME does not point to a Java 17 JDK" in output.out
    assert output.out.endswith("****\n")
    assert output.err == ""


@pytest.mark.parametrize(
    "host_os, java_home, error_type",
    [
        ("Linux", Path("tools", "java17"), FileNotFoundError),
        ("Linux", Path("tools", "java17"), NotADirectoryError),
        ("Windows", Path("tools", "java17"), FileNotFoundError),
        ("Windows", Path("tools", "java17"), NotADirectoryError),
        ("Darwin", Path("tools", "java17", "Contents", "Home"), FileNotFoundError),
        ("Darwin", Path("tools", "java17", "Contents", "Home"), NotADirectoryError),
    ],
)
def test_no_javac(mock_tools, host_os, java_home, error_type, tmp_path, capsys):
    """If the JAVA_HOME doesn't point to a location with a bin/javac, the briefcase JDK
    is used."""
    # Mock os
    mock_tools.host_os = host_os

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/nowhere"}

    # Mock return value from javac failing because executable doesn't exist
    # FileNotFoundError is raised if bin/javac doesn't exist.
    # NotADirectoryError is raised if the user-provided path in JAVA_HOME
    #   contains parts that exist in the filesystem but are not a directory.
    mock_tools.subprocess.check_output.side_effect = error_type

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / java_home / "bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JAVA_HOME should point at the Briefcase-provided JDK
    assert mock_tools.java.java_home == tmp_path / java_home

    # A single call was made to check javac
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/nowhere/bin/javac"), "-version"],
    ),

    # Warning is shown for invalid JAVA_HOME
    output = capsys.readouterr()
    assert "WARNING: JAVA_HOME does not point to a JDK" in output.out
    assert output.out.endswith("****\n")
    assert output.err == ""


@pytest.mark.parametrize(
    "host_os, java_home",
    [
        ("Linux", Path("tools", "java17")),
        ("Windows", Path("tools", "java17")),
        ("Darwin", Path("tools", "java17", "Contents", "Home")),
    ],
)
def test_javac_error(mock_tools, host_os, java_home, tmp_path, capsys):
    """If javac can't be executed, the briefcase JDK is used."""
    # Mock os
    mock_tools.host_os = host_os

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/nowhere"}

    # Mock return value from javac failing because executable doesn't exist
    mock_tools.subprocess.check_output.side_effect = subprocess.CalledProcessError(
        returncode=1, cmd="/path/to/java/bin/javac"
    )

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / java_home / "bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert mock_tools.java.java_home == tmp_path / java_home

    # A single call was made to check javac
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/nowhere/bin/javac"), "-version"],
    ),

    # Warning is shown for invalid JAVA_HOME
    output = capsys.readouterr()
    assert "WARNING: Unable to invoke the Java compiler" in output.out
    assert output.out.endswith("****\n")
    assert output.err == ""


@pytest.mark.parametrize(
    "host_os, java_home",
    [
        ("Linux", Path("tools", "java17")),
        ("Windows", Path("tools", "java17")),
        ("Darwin", Path("tools", "java17", "Contents", "Home")),
    ],
)
def test_unparseable_javac_version(mock_tools, host_os, java_home, tmp_path, capsys):
    """If the javac version can't be parsed, the briefcase JDK is used."""
    # Mock os
    mock_tools.host_os = host_os

    # Setup explicit JAVA_HOME
    mock_tools.os.environ = {"JAVA_HOME": "/path/to/nowhere"}

    # Mock return value from javac.
    mock_tools.subprocess.check_output.return_value = "NONSENSE\n"

    # Create a directory to make it look like the Briefcase Java already exists.
    (tmp_path / java_home / "bin").mkdir(parents=True)

    # Create a JDK wrapper by verification
    jdk = JDK.verify(mock_tools)

    # The JDK should have the briefcase JAVA_HOME
    assert jdk.java_home == tmp_path / java_home

    # A single call was made to check javac
    mock_tools.subprocess.check_output.assert_called_once_with(
        [Path("/path/to/nowhere/bin/javac"), "-version"],
    ),

    # No console output (because Briefcase JDK exists)
    output = capsys.readouterr()
    assert (
        "WARNING: Unable to determine the version of Java that is installed"
        in output.out
    )
    assert output.out.endswith("****\n")
    assert output.err == ""


@pytest.mark.parametrize(
    "host_os, host_arch, jdk_url, jhome, is_32bit",
    [
        (
            "Darwin",
            "x86_64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_x64_mac_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17/Contents/Home",
            False,
        ),
        (
            "Darwin",
            "arm64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_aarch64_mac_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17/Contents/Home",
            False,
        ),
        (
            "Linux",
            "x86_64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_x64_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17",
            False,
        ),
        (
            "Linux",
            "aarch64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_aarch64_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17",
            False,
        ),
        (
            "Linux",
            "aarch64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_arm_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17",
            True,
        ),
        (
            "Linux",
            "armv7l",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_arm_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17",
            False,
        ),
        (
            "Linux",
            "armv8l",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_arm_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
            "java17",
            False,
        ),
        (
            "Windows",
            "AMD64",
            "https://github.com/adoptium/temurin17-binaries/releases/download/"
            f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_x64_windows_hotspot_{JDK_RELEASE}_{JDK_BUILD}.zip",
            "java17",
            False,
        ),
    ],
)
def test_successful_jdk_download(
    mock_tools,
    tmp_path,
    capsys,
    host_os,
    host_arch,
    jdk_url,
    jhome,
    is_32bit,
):
    """If needed, a JDK can be downloaded."""
    # Mock host OS and arch
    mock_tools.host_os = host_os
    mock_tools.host_arch = host_arch
    mock_tools.is_32bit_python = is_32bit

    # Mock a JAVA_HOME that won't exist
    # This is only needed to make macOS *not* run /usr/libexec/java_home
    mock_tools.os.environ = {"JAVA_HOME": "/does/not/exist"}

    # Mock the cached download path
    jdk_zip_path = create_zip_file(tmp_path / "download.zip", content=[("jdk", "jdk")])
    mock_tools.file.download = MagicMock(return_value=jdk_zip_path)

    # Create a directory to make it look like Java was downloaded and unpacked.
    (tmp_path / "tools" / f"jdk-{JDK_RELEASE}+{JDK_BUILD}").mkdir(parents=True)

    # Invoke the verify call
    JDK.verify(mock_tools)

    assert mock_tools.java.java_home == tmp_path / "tools" / jhome

    # Console output contains a warning about the bad JDK location
    output = capsys.readouterr()
    assert output.err == ""
    assert "** WARNING: JAVA_HOME does not point to a Java 17 JDK" in output.out

    # Download was invoked
    mock_tools.file.download.assert_called_with(
        url=jdk_url,
        download_path=tmp_path / "tools",
        role="Java 17 JDK",
    )
    # The archive was unpacked
    mock_tools.shutil.unpack_archive.assert_called_with(
        filename=os.fsdecode(jdk_zip_path), extract_dir=os.fsdecode(tmp_path / "tools")
    )
    # The original archive was deleted
    assert not jdk_zip_path.exists()
    # The download URL for JDK exists
    assert_url_resolvable(mock_tools.java.OpenJDK_download_url)


def test_not_installed(mock_tools, tmp_path):
    """If the JDK isn't installed, and install isn't requested, an error is raised."""
    # Mock host OS
    mock_tools.host_os = "Linux"

    # Invoke the verify call. Install is not requested, so this will fail.
    with pytest.raises(MissingToolError):
        JDK.verify(mock_tools, install=False)

    # Download was not invoked
    assert mock_tools.file.download.call_count == 0


def test_jdk_download_failure(mock_tools, tmp_path):
    """If an error occurs downloading the JDK, an error is raised."""
    # Mock Linux x86_64 as the host
    mock_tools.host_os = "Linux"
    mock_tools.host_arch = "x86_64"

    # Mock a failure on download
    mock_tools.file.download = MagicMock(side_effect=NetworkFailure("mock"))

    # Invoking verify_jdk causes a network failure.
    with pytest.raises(NetworkFailure, match="Unable to mock"):
        JDK.verify(mock_tools)

    # That download was attempted
    mock_tools.file.download.assert_called_with(
        url="https://github.com/adoptium/temurin17-binaries/releases/download/"
        f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_x64_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
        download_path=tmp_path / "tools",
        role="Java 17 JDK",
    )
    # No attempt was made to unpack the archive
    assert mock_tools.shutil.unpack_archive.call_count == 0


def test_invalid_jdk_archive(mock_tools, tmp_path):
    """If the JDK download isn't a valid archive, raise an error."""
    # Mock Linux x86_64 as the host
    mock_tools.host_os = "Linux"
    mock_tools.host_arch = "x86_64"

    # Mock the cached download path
    jdk_zip_path = create_zip_file(tmp_path / "download.zip", content=[("jdk", "jdk")])
    mock_tools.file.download = MagicMock(return_value=jdk_zip_path)

    # Mock an unpack failure due to an invalid archive
    mock_tools.shutil.unpack_archive.side_effect = shutil.ReadError

    with pytest.raises(BriefcaseCommandError):
        JDK.verify(mock_tools)

    # The download occurred
    mock_tools.file.download.assert_called_with(
        url="https://github.com/adoptium/temurin17-binaries/releases/download/"
        f"jdk-{JDK_RELEASE}+{JDK_BUILD}/OpenJDK17U-jdk_x64_linux_hotspot_{JDK_RELEASE}_{JDK_BUILD}.tar.gz",
        download_path=tmp_path / "tools",
        role="Java 17 JDK",
    )
    # An attempt was made to unpack the archive.
    mock_tools.shutil.unpack_archive.assert_called_with(
        filename=os.fsdecode(jdk_zip_path),
        extract_dir=os.fsdecode(tmp_path / "tools"),
    )
    # The original archive was not deleted
    assert jdk_zip_path.exists()