xref: /unit/test/unit/applications/lang/go.py (revision 2073:bc6ad31ce286)
1import os
2import shutil
3import subprocess
4
5from unit.applications.proto import TestApplicationProto
6from unit.option import option
7
8
9class TestApplicationGo(TestApplicationProto):
10    @staticmethod
11    def prepare_env(script, name='app', static=False):
12        temp_dir = option.temp_dir + '/go/'
13
14        if not os.path.exists(temp_dir):
15            os.mkdir(temp_dir)
16
17        cache_dir = option.cache_dir + '/go-build'
18
19        if not os.path.exists(cache_dir):
20            os.mkdir(cache_dir)
21
22        env = os.environ.copy()
23        env['GOPATH'] = option.current_dir + '/build/go'
24        env['GOCACHE'] = cache_dir
25
26        shutil.copy2(
27            option.test_dir + '/go/' + script + '/' + name + '.go', temp_dir
28        )
29
30        if static:
31            args = [
32                'go',
33                'build',
34                '-tags',
35                'netgo',
36                '-ldflags',
37                '-extldflags "-static"',
38                '-o',
39                temp_dir + name,
40                temp_dir + name + '.go',
41            ]
42        else:
43            args = [
44                'go',
45                'build',
46                '-o',
47                temp_dir + name,
48                temp_dir + name + '.go',
49            ]
50
51        replace_path = option.current_dir + '/build/go/src/unit.nginx.org/go'
52
53        with open(temp_dir + 'go.mod', 'w') as f:
54            f.write(
55                f"""module test/app
56require unit.nginx.org/go v0.0.0
57replace unit.nginx.org/go => {replace_path}
58"""
59            )
60
61        if option.detailed:
62            print("\n$ GOPATH=" + env['GOPATH'] + " " + " ".join(args))
63
64        try:
65            process = subprocess.run(args, env=env, cwd=temp_dir)
66
67        except KeyboardInterrupt:
68            raise
69
70        except subprocess.CalledProcessError:
71            return None
72
73        return process
74
75    def load(self, script, name='app', **kwargs):
76        static_build = False
77
78        wdir = option.test_dir + "/go/" + script
79        executable = option.temp_dir + "/go/" + name
80
81        if 'isolation' in kwargs and 'rootfs' in kwargs['isolation']:
82            wdir = "/go/"
83            executable = "/go/" + name
84            static_build = True
85
86        TestApplicationGo.prepare_env(script, name, static=static_build)
87
88        conf = {
89            "listeners": {"*:7080": {"pass": "applications/" + script}},
90            "applications": {
91                script: {
92                    "type": "external",
93                    "processes": {"spare": 0},
94                    "working_directory": wdir,
95                    "executable": executable,
96                },
97            },
98        }
99
100        self._load_conf(conf, **kwargs)
101