summaryrefslogtreecommitdiffstats
path: root/tests/test_scripts.py
blob: 2da6577ee8be249e3489534cabde2c019c30d82e (plain)
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
import io
import os
import zipfile

import pytest

from installer import _scripts
from installer.scripts import InvalidScript, Script


def test_script_generate_simple():
    script = Script("foo", "foo.bar", "baz.qux", section="console")
    name, data = script.generate("/path/to/my/python", kind="posix")

    assert name == "foo"
    assert data.startswith(b"#!/path/to/my/python\n")
    assert b"\nfrom foo.bar import baz\n" in data
    assert b"baz.qux()" in data


def test_script_generate_space_in_executable():
    script = Script("foo", "foo.bar", "baz.qux", section="console")
    name, data = script.generate("/path to my/python", kind="posix")

    assert name == "foo"
    assert data.startswith(b"#!/bin/sh\n")
    assert b" '/path to my/python'" in data
    assert b"\nfrom foo.bar import baz\n" in data
    assert b"baz.qux()" in data


def _read_launcher_data(section, kind):
    prefix = {"console": "t", "gui": "w"}[section]
    suffix = {"win-ia32": "32", "win-amd64": "64", "win-arm": "_arm"}[kind]
    filename = os.path.join(
        os.path.dirname(os.path.abspath(_scripts.__file__)),
        f"{prefix}{suffix}.exe",
    )
    with open(filename, "rb") as f:
        return f.read()


@pytest.mark.parametrize("section", ["console", "gui"])
@pytest.mark.parametrize("kind", ["win-ia32", "win-amd64", "win-arm"])
def test_script_generate_launcher(section, kind):
    launcher_data = _read_launcher_data(section, kind)

    script = Script("foo", "foo.bar", "baz.qux", section=section)
    name, data = script.generate("#!C:\\path to my\\python.exe\n", kind=kind)

    prefix_len = len(launcher_data) + len(b"#!C:\\path to my\\python.exe\n")
    stream = io.BytesIO(data[prefix_len:])
    with zipfile.ZipFile(stream) as zf:
        code = zf.read("__main__.py")

    assert name == "foo.exe"
    assert data.startswith(launcher_data)
    assert b"#!C:\\path to my\\python.exe\n" in data
    assert b"\nfrom foo.bar import baz\n" in code
    assert b"baz.qux()" in code


@pytest.mark.parametrize(
    "section, kind",
    [("nonexist", "win-ia32"), ("console", "nonexist"), ("nonexist", "nonexist")],
)
def test_script_generate_launcher_error(section, kind):
    script = Script("foo", "foo.bar", "baz.qux", section=section)
    with pytest.raises(InvalidScript):
        script.generate("#!C:\\path to my\\python.exe\n", kind=kind)