v2 / vlib / v / pref / vsh_envbang_test.v
88 lines · 82 sloc · 2.61 KB · e2e5cf8db56f3562c7baa735061690be936bdf3e
Raw
1import os
2import rand
3
4const vexe = @VEXE
5
6fn testsuite_begin() {
7 $if windows {
8 skip_test('windows does not support envbang lines')
9 }
10 // Make sure, that we will be using the local v, instead of the globally installed one,
11 // for the rest of the tests here:
12 local_v_path := os.dir(vexe)
13 old_path := os.getenv('PATH')
14 os.setenv('PATH', '${local_v_path}:${old_path}', true)
15 println('Changed PATH: ${os.getenv('PATH')}')
16}
17
18fn test_envbang_script_runs() {
19 env_location := '/usr/bin/env'
20 if !os.exists(env_location) {
21 skip_test('${env_location} does not exist')
22 }
23 if !os.is_executable(env_location) {
24 skip_test('${env_location} is not executable')
25 }
26 os.find_abs_path_of_executable('v') or { skip_test('v is not in PATH') }
27 rndname := rand.ulid()
28 rnd_vsh_script_path := os.real_path(os.join_path(os.cache_dir(), '${rndname}.vsh'))
29 os.write_file(rnd_vsh_script_path, "#!${env_location} v
30import os
31println('hello')
32println('@VEXE: ${vexe}')
33println(os.args)
34")!
35 os.chmod(rnd_vsh_script_path, 0o700)!
36 res := os.execute('${os.quoted_path(rnd_vsh_script_path)} abc 123 -option')
37 assert res.exit_code == 0
38 lines := res.output.split_into_lines()
39 dump(lines)
40 assert lines[0] == 'hello'
41 assert lines[1].starts_with('@VEXE: ')
42 assert os.real_path(lines[1].all_after('@VEXE: ')) == os.real_path(vexe)
43 assert lines[2].ends_with(", 'abc', '123', '-option']")
44 os.rm(rnd_vsh_script_path)!
45}
46
47fn test_envbang_script_accepts_existing_file_paths() {
48 env_location := '/usr/bin/env'
49 if !os.exists(env_location) {
50 skip_test('${env_location} does not exist')
51 }
52 if !os.is_executable(env_location) {
53 skip_test('${env_location} is not executable')
54 }
55 os.find_abs_path_of_executable('v') or { skip_test('v is not in PATH') }
56 rndname := rand.ulid()
57 rnd_vsh_script_path := os.real_path(os.join_path(os.cache_dir(), '${rndname}.vsh'))
58 existing_path := os.real_path(os.join_path(os.cache_dir(), '${rndname}.txt'))
59 os.write_file(rnd_vsh_script_path, "#!${env_location} v
60import os
61import flag
62
63fn main() {
64 mut fp := flag.new_flag_parser(os.args)
65 fp.skip_executable()
66 file_path := fp.string('path', `p`, '', 'The path to the file to read')
67 fp.finalize() or {
68 eprintln(err)
69 exit(1)
70 }
71 println('File path: ' + file_path)
72}
73")!
74 os.write_file(existing_path, 'hello')!
75 os.chmod(rnd_vsh_script_path, 0o700)!
76 res :=
77 os.execute('${os.quoted_path(rnd_vsh_script_path)} --path ${os.quoted_path(existing_path)}')
78 assert res.exit_code == 0
79 assert res.output.trim_space() == 'File path: ${existing_path}'
80 os.rm(rnd_vsh_script_path)!
81 os.rm(existing_path)!
82}
83
84@[noreturn]
85fn skip_test(reason string) {
86 println('skipping test, because ${reason} .')
87 exit(0)
88}
89