File: test_LocalRequirementsMixin.py

package info (click to toggle)
python-briefcase 0.3.25-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,596 kB
  • sloc: python: 62,519; makefile: 60
file content (479 lines) | stat: -rw-r--r-- 15,743 bytes parent folder | download
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
import shutil
import subprocess
import sys
from pathlib import Path
from unittest.mock import MagicMock, call

import pytest

from briefcase.commands import CreateCommand
from briefcase.exceptions import BriefcaseCommandError
from briefcase.integrations.docker import Docker, DockerAppContext
from briefcase.integrations.subprocess import Subprocess
from briefcase.platforms.linux import LocalRequirementsMixin

from ...utils import create_file, create_tgz_file, create_zip_file


class DummyCreateCommand(LocalRequirementsMixin, CreateCommand):
    """A command that provides the stubs required to satisfy LocalRequirementsMixin."""

    platform = "Tester"
    output_format = "Dummy"

    def binary_path(self, app):
        return self.bundle_path(app) / f"{app.app_name}.bin"


@pytest.fixture
def no_docker_create_command(dummy_console, first_app_config, tmp_path):
    command = DummyCreateCommand(
        console=dummy_console,
        base_path=tmp_path / "base_path",
        data_path=tmp_path / "briefcase",
    )

    # Disable Docker use
    command.use_docker = False

    # Set the host architecture to something known for test purposes.
    command.tools.host_arch = "wonky"

    # Set the host system to Linux for test purposes
    command.tools.host_os = "Linux"

    # Mock the existence of Docker
    command.tools.subprocess = MagicMock(spec_set=Subprocess)

    # Mock shutil.copy to do the copy, but be observable
    command.tools.shutil.copy = MagicMock(side_effect=shutil.copy)

    command._briefcase_toml[first_app_config] = {
        "paths": {"app_packages_path": "path/to/app_packages"}
    }

    # At the time app requirements are installed, the project folder will exist.
    command.bundle_path(first_app_config).mkdir(parents=True, exist_ok=True)

    return command


@pytest.fixture
def create_command(no_docker_create_command, first_app_config, tmp_path, monkeypatch):
    # Enable Docker use
    no_docker_create_command.use_docker = True

    # Provide Docker
    monkeypatch.setattr(
        Docker, "_is_user_mapping_enabled", MagicMock(return_value=True)
    )
    no_docker_create_command.tools.docker = Docker(tools=no_docker_create_command.tools)
    # Provide Docker app context
    no_docker_create_command.tools[first_app_config].app_context = DockerAppContext(
        tools=no_docker_create_command.tools,
        app=first_app_config,
    )
    no_docker_create_command.tools[first_app_config].app_context.prepare(
        image_tag="briefcase/com.example.first-app:py3.X",
        dockerfile_path=tmp_path / "base_path/build/first-app/tester/dummy/Dockerfile",
        app_base_path=tmp_path / "base_path",
        host_bundle_path=tmp_path / "base_path/build/first-app/tester/dummy",
        host_data_path=tmp_path / "briefcase",
        python_version="3.X",
    )

    # Reset the subprocess.run mock, removing the Docker setup call
    no_docker_create_command.tools.subprocess.run.reset_mock()

    return no_docker_create_command


@pytest.fixture
def first_package(tmp_path):
    # Create a local package to be built
    create_file(
        tmp_path / "local/first/setup.py",
        content="Python config",
    )
    create_file(
        tmp_path / "local/first/first.py",
        content="Python source",
    )

    return str(tmp_path / "local/first")


@pytest.fixture
def second_package(tmp_path):
    # Create a local pre-built sdist
    create_tgz_file(
        tmp_path / "local/second-2.3.4.tar.gz",
        content=[
            ("setup.py", "Python config"),
            ("second.py", "Python source"),
        ],
    )

    return str(tmp_path / "local/second-2.3.4.tar.gz")


@pytest.fixture
def third_package(tmp_path):
    # Create a local pre-built wheel
    create_zip_file(
        tmp_path / "local/third-3.4.5-py3-none-any.whl",
        content=[
            ("MANIFEST.in", "Wheel config"),
            ("third.py", "Python source"),
        ],
    )

    return str(tmp_path / "local/third-3.4.5-py3-none-any.whl")


@pytest.fixture
def other_package(create_command, first_app_config):
    # A stale sdist, built in a previous pass
    create_tgz_file(
        create_command.local_requirements_path(first_app_config)
        / "other_package-0.1.2.tar.gz",
        content=[
            ("setup.py", "Python config"),
            ("other.py", "Python source"),
        ],
    )


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_in_docker(create_command, first_app_config, tmp_path):
    """If Docker is in use, a docker context is used to invoke pip."""

    # Install requirements
    create_command.install_app_requirements(first_app_config)

    # pip was invoked inside docker.
    create_command.tools.subprocess.run.assert_called_once_with(
        args=[
            "docker",
            "run",
            "--rm",
            "--volume",
            f"{tmp_path / 'base_path/build/first-app/tester/dummy'}:/app:z",
            "--volume",
            f"{tmp_path / 'briefcase'}:/briefcase:z",
            "briefcase/com.example.first-app:py3.X",
            "python3.X",
            "-u",
            "-X",
            "utf8",
            "-m",
            "pip",
            "install",
            "--disable-pip-version-check",
            "--upgrade",
            "--no-user",
            "--target=/app/path/to/app_packages",
            "foo==1.2.3",
            "bar>=4.5",
        ],
        check=True,
        encoding="UTF-8",
        env={"DOCKER_CLI_HINTS": "false"},
    )

    # The local requirements path exists, but is empty
    local_requirements_path = create_command.local_requirements_path(first_app_config)
    assert local_requirements_path.exists()
    assert len(list(local_requirements_path.iterdir())) == 0


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_no_docker(
    no_docker_create_command,
    first_app_config,
    tmp_path,
):
    """If docker is *not* in use, calls are made on raw subprocess."""
    # Verify the tools; this should operate in the non-docker context
    no_docker_create_command.verify_tools()
    no_docker_create_command.verify_app_tools(first_app_config)

    # Install requirements
    no_docker_create_command.install_app_requirements(first_app_config)

    # Docker is not verified.
    assert not hasattr(no_docker_create_command.tools, "docker")

    # Subprocess is used for app_context
    assert isinstance(
        no_docker_create_command.tools[first_app_config].app_context, Subprocess
    )
    assert (
        no_docker_create_command.tools[first_app_config].app_context
        is no_docker_create_command.tools.subprocess
    )

    # pip was invoked natively
    no_docker_create_command.tools[
        first_app_config
    ].app_context.run.assert_called_once_with(
        [
            sys.executable,
            "-u",
            "-X",
            "utf8",
            "-m",
            "pip",
            "install",
            "--disable-pip-version-check",
            "--upgrade",
            "--no-user",
            f"--target={tmp_path / 'base_path/build/first-app/tester/dummy/path/to/app_packages'}",
            "foo==1.2.3",
            "bar>=4.5",
        ],
        check=True,
        encoding="UTF-8",
    )

    # The local requirements path exists, but is empty
    local_requirements_path = no_docker_create_command.local_requirements_path(
        first_app_config
    )
    assert local_requirements_path.exists()
    assert len(list(local_requirements_path.iterdir())) == 0


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_with_locals(
    create_command,
    first_app_config,
    tmp_path,
    first_package,  # A local folder to be built
    second_package,  # A pre-built sdist
    third_package,  # A pre-built wheel
    other_package,  # A stale local requirement
):
    """If the app has local requirements, they are compiled into sdists for
    installation."""
    # Add local requirements
    first_app_config.requires.extend([first_package, second_package, third_package])

    # Mock the side effect of building an sdist
    def build_sdist(*args, **kwargs):
        # Extract the folder name; assume that's the name of the package
        name = Path(args[0][-1]).name
        create_tgz_file(
            create_command.local_requirements_path(first_app_config)
            / f"{name}-1.2.3.tar.gz",
            content=[
                ("setup.py", "Python config"),
                ("local.py", "Python source"),
            ],
        )

    create_command.tools.subprocess.check_output.side_effect = build_sdist

    # Install requirements
    create_command.install_app_requirements(first_app_config)

    # An sdist was built for the local package
    create_command.tools.subprocess.check_output.assert_called_once_with(
        [
            sys.executable,
            "-X",
            "utf8",
            "-m",
            "build",
            "--sdist",
            "--outdir",
            tmp_path / "base_path/build/first-app/tester/dummy/_requirements",
            str(tmp_path / "local/first"),
        ],
        encoding="UTF-8",
    )

    # An attempt was made to copy the prebuilt packages
    create_command.tools.shutil.copy.mock_calls = [
        call(
            str(tmp_path / "local/second-2.3.4.tar.gz"),
            tmp_path / "base_path/build/first-app/tester/dummy/_requirements",
        ),
        call(
            str(tmp_path / "local/third-3.4.5-py3-none-any.whl"),
            tmp_path / "base_path/build/first-app/tester/dummy/_requirements",
        ),
    ]

    # pip was invoked inside docker.
    create_command.tools.subprocess.run.assert_called_once_with(
        args=[
            "docker",
            "run",
            "--rm",
            "--volume",
            f"{tmp_path / 'base_path/build/first-app/tester/dummy'}:/app:z",
            "--volume",
            f"{tmp_path / 'briefcase'}:/briefcase:z",
            "briefcase/com.example.first-app:py3.X",
            "python3.X",
            "-u",
            "-X",
            "utf8",
            "-m",
            "pip",
            "install",
            "--disable-pip-version-check",
            "--upgrade",
            "--no-user",
            "--target=/app/path/to/app_packages",
            "foo==1.2.3",
            "bar>=4.5",
            "/app/_requirements/first-1.2.3.tar.gz",
            "/app/_requirements/second-2.3.4.tar.gz",
            "/app/_requirements/third-3.4.5-py3-none-any.whl",
        ],
        check=True,
        encoding="UTF-8",
        env={"DOCKER_CLI_HINTS": "false"},
    )

    # The local requirements path exists, and contains the compiled sdist, the
    # pre-existing sdist, and the pre-existing wheel; the old requirement has
    # been purged.
    local_requirements_path = create_command.local_requirements_path(first_app_config)
    assert local_requirements_path.exists()
    assert [f.name for f in sorted(local_requirements_path.iterdir())] == [
        "first-1.2.3.tar.gz",
        "second-2.3.4.tar.gz",
        "third-3.4.5-py3-none-any.whl",
    ]


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_with_bad_local(
    create_command,
    first_app_config,
    tmp_path,
    first_package,  # A local folder to be built
    other_package,  # A stale local requirement
):
    """If the app has local requirement that can't be built, an error is raised."""
    # Add a local requirement
    first_app_config.requires.append(first_package)

    # Mock the building an sdist raising an error
    create_command.tools.subprocess.check_output.side_effect = (
        subprocess.CalledProcessError(
            cmd=["python", "-m", "build", "..."], returncode=1
        )
    )

    # Install requirements
    with pytest.raises(
        BriefcaseCommandError,
        match=r"Unable to build sdist for .*/local/first",
    ):
        create_command.install_app_requirements(first_app_config)

    # An attempt to build the sdist was made
    create_command.tools.subprocess.check_output.assert_called_once_with(
        [
            sys.executable,
            "-X",
            "utf8",
            "-m",
            "build",
            "--sdist",
            "--outdir",
            tmp_path / "base_path/build/first-app/tester/dummy/_requirements",
            str(tmp_path / "local/first"),
        ],
        encoding="UTF-8",
    )

    # pip was *not* invoked inside docker.
    create_command.tools.subprocess.run.assert_not_called()

    # The local requirements path exists, and is empty. It has been purged, but not refilled.
    local_requirements_path = create_command.local_requirements_path(first_app_config)
    assert local_requirements_path.exists()
    assert len(list(local_requirements_path.iterdir())) == 0


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_with_missing_local_build(
    create_command,
    first_app_config,
    tmp_path,
):
    """If the app references a requirement that needs to be built, but is missing, an
    error is raised."""
    # Define a local requirement, but don't create the files it points at
    first_app_config.requires.append(str(tmp_path / "local/first"))

    # Install requirements
    with pytest.raises(
        BriefcaseCommandError,
        match=r"Unable to find local requirement .*/local/first",
    ):
        create_command.install_app_requirements(first_app_config)

    # No attempt to build the sdist was made
    create_command.tools.subprocess.check_output.assert_not_called()

    # pip was *not* invoked inside docker.
    create_command.tools.subprocess.run.assert_not_called()

    # The local requirements path exists, and is empty. It has been purged, but not refilled.
    local_requirements_path = create_command.local_requirements_path(first_app_config)
    assert local_requirements_path.exists()
    assert len(list(local_requirements_path.iterdir())) == 0


@pytest.mark.skipif(
    sys.platform == "win32", reason="Windows paths aren't converted in Docker context"
)
def test_install_app_requirements_with_bad_local_file(
    create_command,
    first_app_config,
    tmp_path,
):
    """If the app references a local requirement file that doesn't exist, an error is
    raised."""
    # Add a local requirement that doesn't exist
    first_app_config.requires.append(str(tmp_path / "local/missing-2.3.4.tar.gz"))

    # Install requirements
    with pytest.raises(
        BriefcaseCommandError,
        match=r"Unable to find local requirement .*/local/missing-2.3.4.tar.gz",
    ):
        create_command.install_app_requirements(first_app_config)

    # An attempt was made to copy the package
    create_command.tools.shutil.copy.assert_called_once_with(
        str(tmp_path / "local/missing-2.3.4.tar.gz"),
        tmp_path / "base_path/build/first-app/tester/dummy/_requirements",
    )

    # No attempt was made to build the sdist
    create_command.tools.subprocess.check_output.assert_not_called()

    # pip was *not* invoked inside docker.
    create_command.tools.subprocess.run.assert_not_called()

    # The local requirements path exists, and is empty. It has been purged, but not refilled.
    local_requirements_path = create_command.local_requirements_path(first_app_config)
    assert local_requirements_path.exists()
    assert len(list(local_requirements_path.iterdir())) == 0