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
|
import subprocess
from collections import namedtuple
from pathlib import Path
from unittest.mock import MagicMock, call
import pytest
from briefcase.exceptions import BriefcaseCommandError, UnsupportedHostError
from briefcase.integrations.base import ToolCache
from briefcase.integrations.docker import Docker
from briefcase.integrations.subprocess import Subprocess
DOCKER_VERSION_MIN = "20.10"
VALID_DOCKER_VERSION = f"Docker version {DOCKER_VERSION_MIN}, build afacb8b\n"
VALID_DOCKER_INFO = "docker info printout"
VALID_BUILDX_VERSION = "github.com/docker/buildx v0.10.2 00ed17d\n"
VALID_USER_MAPPING_IMAGE_CACHE = "1ed313b0551f"
DOCKER_VERIFICATION_CALLS = [
call(["docker", "--version"], env={"DOCKER_CLI_HINTS": "false"}),
call(["docker", "info"], env={"DOCKER_CLI_HINTS": "false"}, quiet=1),
call(["docker", "buildx", "version"], env={"DOCKER_CLI_HINTS": "false"}),
]
@pytest.fixture
def mock_tools(mock_tools) -> ToolCache:
mock_tools.subprocess = MagicMock(spec_set=Subprocess)
return mock_tools
@pytest.fixture
def mock_write_test_path(tmp_path, monkeypatch):
"""Mock the container write test path in to pytest's tmp directory."""
write_test_path = tmp_path / "mock_write_test"
# Wrap the path so read-only methods can be replaced
write_test_path = MagicMock(wraps=write_test_path)
monkeypatch.setattr(Docker, "_write_test_path", lambda self: write_test_path)
return write_test_path
def test_short_circuit(mock_tools):
"""Tool is not created if already cached."""
mock_tools.docker = "tool"
tool = Docker.verify(mock_tools)
assert tool == "tool"
assert tool == mock_tools.docker
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"{Docker.name} is not supported on wonky",
):
Docker.verify(mock_tools)
@pytest.mark.parametrize("host_os", ["Windows", "Linux", "Darwin"])
def test_docker_install_url(host_os):
"""Docker details available for each OS."""
assert host_os in Docker.DOCKER_INSTALL_URL
@pytest.mark.parametrize(
"version_output",
[
VALID_DOCKER_VERSION,
# Docker version format on Ubuntu
"Docker version 26.1.1, build 4cf5afa",
# Docker version format on OpenSUSE Tumbleweed
"Docker version 26.1.0-ce, build c8af8ebe4a89",
],
)
def test_docker_exists(mock_tools, user_mapping_run_calls, version_output, capsys):
"""If docker exists, the Docker wrapper is returned."""
# Mock the return value of Docker Version
mock_tools.subprocess.check_output.side_effect = [
version_output,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
"", # touch host_write_file
"", # rm -f host_write_file
]
# Invoke docker verify
result = Docker.verify(mock_tools)
# The verify call should return the Docker wrapper
assert isinstance(result, Docker)
# Docker version and plugins were verified and user mapping inspection occurred
mock_tools.subprocess.check_output.assert_has_calls(
DOCKER_VERIFICATION_CALLS + user_mapping_run_calls
)
# No console output
output = capsys.readouterr()
assert output.out == ""
assert output.err == ""
def test_docker_doesnt_exist(mock_tools):
"""If docker doesn't exist, an error is raised."""
# Mock Docker not installed on system
mock_tools.subprocess.check_output.side_effect = FileNotFoundError
# Invoke Docker verify
with pytest.raises(BriefcaseCommandError):
Docker.verify(mock_tools)
# But docker was invoked
mock_tools.subprocess.check_output.assert_called_with(
["docker", "--version"], env={"DOCKER_CLI_HINTS": "false"}
)
def test_docker_failure(mock_tools, user_mapping_run_calls, capsys):
"""If docker failed during execution, the Docker wrapper is returned with a
warning."""
# Mock Docker cannot be found
mock_tools.subprocess.check_output.side_effect = [
subprocess.CalledProcessError(
returncode=1,
cmd="docker --version",
),
"Success!",
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
"", # touch host_write_file
"", # rm -f host_write_file
]
# Invoke Docker verify
result = Docker.verify(mock_tools)
# The verify call should return the Docker wrapper
assert isinstance(result, Docker)
# Docker version and plugins were verified and user mapping inspection occurred
mock_tools.subprocess.check_output.assert_has_calls(
DOCKER_VERIFICATION_CALLS + user_mapping_run_calls
)
# console output
output = capsys.readouterr()
assert "** WARNING: Unable to determine if Docker is installed" in output.out
assert output.err == ""
def test_docker_bad_version(mock_tools, capsys):
"""If docker exists but the version string doesn't make sense, the Docker wrapper is
returned with a warning."""
# Mock a bad return value of `docker --version`
mock_tools.subprocess.check_output.return_value = "Docker version 19.03.8, build\n"
# Invoke Docker verify
with pytest.raises(
BriefcaseCommandError,
match=rf"Briefcase requires Docker {DOCKER_VERSION_MIN} or higher",
):
Docker.verify(mock_tools)
def test_docker_unknown_version(mock_tools, user_mapping_run_calls, capsys):
"""If docker exists but the version string doesn't make sense, the Docker wrapper is
returned with a warning."""
# Mock a bad return value of `docker --version`
mock_tools.subprocess.check_output.return_value = "ceci nest pas un Docker\n"
# Invoke Docker verify
result = Docker.verify(mock_tools)
# The verify call should return the Docker wrapper
assert isinstance(result, Docker)
# Docker version and plugins were verified and user mapping inspection occurred
mock_tools.subprocess.check_output.assert_has_calls(
DOCKER_VERIFICATION_CALLS + user_mapping_run_calls
)
# console output
output = capsys.readouterr()
assert "** WARNING: Unable to determine the version of Docker" in output.out
assert output.err == ""
def test_docker_exists_but_process_lacks_permission_to_use_it(mock_tools):
"""If the docker daemon isn't running, the check fails."""
error_message = """
Client:
Debug Mode: false
Server:
ERROR: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock:
Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/info: dial unix /var/run/docker.sock: connect: permission denied
errors pretty printing info"""
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
subprocess.CalledProcessError(
returncode=1,
cmd="docker info",
output=error_message,
),
]
with pytest.raises(
BriefcaseCommandError,
match="does not have\npermissions to invoke Docker.",
):
Docker.verify(mock_tools)
@pytest.mark.parametrize(
"error_message",
[
"""
Client:
Debug Mode: false
Server:
ERROR: Error response from daemon: dial unix docker.raw.sock: connect: connection refused
errors pretty printing info
""", # this is the error shown on mac
"""
Client:
Debug Mode: false
Server:
ERROR: Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
errors pretty printing info""", # this is the error show on linux
],
)
def test_docker_exists_but_is_not_running(error_message, mock_tools):
"""If the docker daemon isn't running, the check fails."""
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
subprocess.CalledProcessError(
returncode=1,
cmd="docker info",
output=error_message,
),
]
with pytest.raises(
BriefcaseCommandError,
match="the Docker\ndaemon is not running",
):
Docker.verify(mock_tools)
def test_docker_exists_but_unknown_error_when_running_command(mock_tools):
"""If docker info fails in unknown ways, the check fails."""
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
subprocess.CalledProcessError(
returncode=1,
cmd="docker info",
output="This command failed!",
),
]
with pytest.raises(
BriefcaseCommandError,
match="Check your Docker\ninstallation, and try again",
):
Docker.verify(mock_tools)
def test_buildx_plugin_not_installed(mock_tools):
"""If the buildx plugin is not installed, verification fails."""
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
subprocess.CalledProcessError(
returncode=1,
cmd="docker buildx version",
),
]
with pytest.raises(
BriefcaseCommandError,
match="Docker is installed and available for use but the buildx plugin\nis not installed",
):
Docker.verify(mock_tools)
def test_docker_image_hint(mock_tools):
"""If an image_tag is passed to verification, it is used for the user mapping
check."""
# Mock the return values for Docker verification
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
"", # touch host_write_file
"", # rm -f host_write_file
]
Docker.verify(mock_tools, image_tag="myimage:tagtorulethemall")
mock_tools.subprocess.check_output.assert_has_calls(
DOCKER_VERIFICATION_CALLS
+ [
call(
["docker", "images", "-q", "myimage:tagtorulethemall"],
env={"DOCKER_CLI_HINTS": "false"},
),
call(
args=[
"docker",
"run",
"--rm",
"--volume",
f"{Path.cwd() / 'build'}:/host_write_test:z",
"myimage:tagtorulethemall",
"touch",
"/host_write_test/container_write_test",
],
env={"DOCKER_CLI_HINTS": "false"},
),
call(
args=[
"docker",
"run",
"--rm",
"--volume",
f"{Path.cwd() / 'build'}:/host_write_test:z",
"myimage:tagtorulethemall",
"rm",
"-f",
"/host_write_test/container_write_test",
],
env={"DOCKER_CLI_HINTS": "false"},
),
]
)
def test_user_mapping_write_file_path(mock_tools):
"""The write test file path is as expected."""
expected_path = Path.cwd() / "build/container_write_test"
assert Docker(mock_tools)._write_test_path() == expected_path
def test_user_mapping_write_file_exists(mock_tools, mock_write_test_path):
"""Docker verification fails when the container write test file exists and cannot be
deleted."""
# Mock the return values for Docker verification
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
]
# Mock failure for deleting an existing write test file
mock_write_test_path.unlink = MagicMock(side_effect=OSError("delete failed"))
# Fails when file cannot be deleted
with pytest.raises(
BriefcaseCommandError,
match="file path used to determine how Docker is mapping users",
):
Docker.verify(mock_tools)
def test_user_mapping_write_test_file_creation_fails(mock_tools, mock_write_test_path):
"""Docker verification fails if the write test file cannot be written."""
# Mock the return values for Docker verification
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
# Mock failure for deleting an existing write test file
subprocess.CalledProcessError(returncode=1, cmd=["docker", "run", "..."]),
]
# Fails when file cannot be deleted
with pytest.raises(
BriefcaseCommandError,
match="Unable to determine if Docker is mapping users",
):
Docker.verify(mock_tools)
def test_user_mapping_write_test_file_cleanup_fails(mock_tools, mock_write_test_path):
"""Docker verification fails if the write test file cannot be removed after the
test."""
# Mock the return values for Docker verification
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
# Mock failure for deleting an existing write test file
"", # touch host_write_file
subprocess.CalledProcessError(returncode=1, cmd=["docker", "run", "..."]),
]
# Fails when file cannot be deleted
with pytest.raises(
BriefcaseCommandError,
match="Unable to clean up from determining if Docker is mapping users",
):
Docker.verify(mock_tools)
@pytest.mark.parametrize("file_owner_id, expected", [(1000, True), (0, False)])
def test_user_mapping_setting(
mock_tools,
user_mapping_run_calls,
file_owner_id,
expected,
):
"""If the write test file is not owned by root, user mapping is enabled, else
disabled."""
# Mock the return values for Docker verification
mock_tools.subprocess.check_output.side_effect = [
VALID_DOCKER_VERSION,
VALID_DOCKER_INFO,
VALID_BUILDX_VERSION,
VALID_USER_MAPPING_IMAGE_CACHE,
"", # touch host_write_file
"", # rm -f host_write_file
]
stat_result = namedtuple("stat_result", "st_uid")
# Mock the os.stat call returning a file owned by file_owner_id
mock_tools.os.stat = MagicMock(return_value=stat_result(st_uid=file_owner_id))
docker = Docker.verify(mock_tools)
# Docker user mapping inspection occurred
mock_tools.subprocess.check_output.assert_has_calls(
DOCKER_VERIFICATION_CALLS + user_mapping_run_calls
)
assert docker.is_user_mapped is expected
|