v2 / vlib / os / find_abs_path_of_executable_test.v
87 lines · 68 sloc · 2.33 KB · 1c5a9e1be23dcb37e9d2789deaf171cb0104f7f7
Raw
1import os
2
3const tfolder = os.join_path(os.real_path(os.vtmp_dir()), 'filepath_tests')
4const original_path = os.getenv('PATH')
5
6fn testsuite_begin() {
7 eprintln('testsuite_begin, tfolder = ${tfolder}')
8 os.rmdir_all(tfolder) or {}
9 os.mkdir_all(tfolder) or { panic(err) }
10 os.chdir(tfolder) or { panic(err) }
11}
12
13fn testsuite_end() {
14 os.chdir(os.wd_at_startup) or {}
15 os.rmdir_all(tfolder) or {}
16}
17
18fn test_find_abs_path_of_executable() {
19 exefolder := os.join_path(tfolder, 'exe')
20 os.mkdir(exefolder) or { panic(err) }
21
22 mut myclang_file := os.join_path(exefolder, 'myclang')
23 $if windows {
24 myclang_file += '.bat'
25 }
26
27 mut mylink_file := os.join_path(tfolder, 'mylink')
28 $if windows {
29 mylink_file += '.bat'
30 }
31
32 os.write_file(myclang_file, 'echo hello')!
33 os.chmod(myclang_file, 0o0777)!
34 dump(os.abs_path(myclang_file))
35 dump(os.real_path(myclang_file))
36 dump(os.is_executable(myclang_file))
37
38 $if windows {
39 eprintln('Windows requires admin privileges in order to create symlinks, related tests will be faked.')
40 os.cp(myclang_file, mylink_file) or { panic(err) }
41 } $else {
42 os.symlink(myclang_file, mylink_file) or { panic(err) }
43 }
44
45 dump(os.abs_path(mylink_file))
46 dump(os.real_path(mylink_file))
47 dump(os.is_executable(mylink_file))
48
49 prepend_to_original_path(exefolder)
50 assert find_and_check('myclang')? == myclang_file
51 assert find_and_check('mylink') == none
52
53 prepend_to_original_path('.')
54 assert find_and_check('mylink')? == mylink_file
55 assert find_and_check('myclang') == none
56
57 os.chdir(exefolder) or { panic(err) }
58 assert find_and_check('myclang')? == myclang_file
59 assert find_and_check('mylink') == none
60
61 prepend_to_original_path(tfolder)
62 assert find_and_check('mylink')? == mylink_file
63 assert find_and_check('myclang') == none
64
65 restore_original_path()
66 os.chdir(os.home_dir())! // Change to a *completely* different folder, just in case the original PATH contains `.`
67 assert find_and_check('myclang') == none
68 assert find_and_check('mylink') == none
69}
70
71fn find_and_check(executable string) ?string {
72 fpath := os.find_abs_path_of_executable(executable) or { return none }
73
74 dump(fpath)
75 assert os.is_abs_path(fpath)
76
77 return fpath
78}
79
80fn restore_original_path() {
81 os.setenv('PATH', original_path, true)
82}
83
84fn prepend_to_original_path(to_prepend string) {
85 new_path := to_prepend + os.path_delimiter + original_path
86 os.setenv('PATH', new_path, true)
87}
88