v2 / vlib / v / fmt / fmt_bin2v_test.v
61 lines · 56 sloc · 1.88 KB · a1f36240b02a062f4cd856a84ce429d66eaf056c
Raw
1import os
2import rand
3import v.ast
4import v.parser
5import v.fmt
6import v.pref
7import v.util.diff
8
9const vexe = os.getenv('VEXE')
10const tmpfolder = os.join_path(os.temp_dir(), 'fmt_bin2v_test')
11const b2v_keep_path = os.join_path(tmpfolder, rand.ulid() + '.vv')
12const ifilename = os.file_name(b2v_keep_path)
13const fpref = &pref.Preferences{
14 is_fmt: true
15}
16
17fn test_bin2v_formatting() {
18 os.mkdir_all(tmpfolder)!
19 defer {
20 os.rmdir_all(tmpfolder) or {}
21 }
22 prepare_bin2v_file()
23
24 mut table := ast.new_table()
25 file_ast := parser.parse_file(b2v_keep_path, mut table, .parse_comments, fpref)
26 result_ocontent := fmt.fmt(file_ast, mut table, fpref, false)
27 eprintln('> the file ${b2v_keep_path} can be formatted.')
28 expected_ocontent := os.read_file(b2v_keep_path)!
29 if expected_ocontent != result_ocontent {
30 vfmt_result_file := os.join_path(tmpfolder, 'vfmt_run_over_${ifilename}')
31 os.write_file(vfmt_result_file, result_ocontent)!
32 println(diff.compare_files(b2v_keep_path, vfmt_result_file)!)
33 exit(1)
34 } else {
35 assert true
36 }
37 println('> vfmt: `v bin2v file.v` produces fully formatted code.')
38}
39
40fn prepare_bin2v_file() {
41 write_bin2v_keep_content() or {
42 eprintln('Failed preparing bin2v_keep.vv: ${err.msg()}')
43 return
44 }
45 eprintln('> prepared ${b2v_keep_path} .')
46}
47
48fn write_bin2v_keep_content() ! {
49 // Note: do not put large files here; the goal of this particular test is
50 // just to guarantee that the output of `v bin2v` is invariant to vfmt, not
51 // to stress out bin2v or vfmt...
52 img0 := os.join_path('vlib', 'v', 'embed_file', 'tests', 'v.png')
53 img1 := os.join_path('examples', 'assets', 'logo.png')
54 os.rm(b2v_keep_path) or {}
55 cmd := '${os.quoted_path(vexe)} bin2v -w ${os.quoted_path(b2v_keep_path)} ${os.quoted_path(img0)} ${os.quoted_path(img1)}'
56 eprintln('> running: ${cmd}')
57 res := os.execute(cmd)
58 if res.exit_code != 0 {
59 return error_with_code(res.output.trim_space(), res.exit_code)
60 }
61}
62