v4 / cmd / tools / modules / testing / common.v
1226 lines · 1118 sloc · 37.67 KB · c0624b274a458fe3e487d89ae9554c2e8c25bdb6
Raw
1module testing
2
3import os
4import os.cmdline
5import semver
6import time
7import term
8import benchmark
9import sync
10import sync.pool
11import v.pref
12import v.util.vtest
13import v.util.vflags
14import runtime
15import rand
16import strings
17import v.build_constraint
18
19pub const max_header_len = get_max_header_len()
20
21pub const host_os = pref.get_host_os()
22
23pub const github_job = os.getenv('GITHUB_JOB')
24
25pub const runner_os = os.getenv('RUNNER_OS') // GitHub runner OS
26
27pub const keep_session = os.getenv('VTEST_KEEP_SESSION') == '1'
28
29pub const show_cmd = os.getenv('VTEST_SHOW_CMD') == '1'
30
31pub const show_start = os.getenv('VTEST_SHOW_START') == '1'
32
33pub const show_longest_by_runtime = os.getenv('VTEST_SHOW_LONGEST_BY_RUNTIME').int()
34pub const show_longest_by_comptime = os.getenv('VTEST_SHOW_LONGEST_BY_COMPTIME').int()
35pub const show_longest_by_totaltime = os.getenv('VTEST_SHOW_LONGEST_BY_TOTALTIME').int()
36
37pub const is_ci = os.getenv('CI') != '' || os.getenv('GITHUB_JOB') != ''
38
39pub const hide_skips = os.getenv('VTEST_HIDE_SKIP') == '1'
40 || (is_ci && os.getenv('VTEST_HIDE_SKIP') != '0')
41
42pub const hide_oks = os.getenv('VTEST_HIDE_OK') == '1'
43 || (is_ci && os.getenv('VTEST_HIDE_OK') != '0')
44
45pub const fail_fast = os.getenv('VTEST_FAIL_FAST') == '1'
46
47pub const fail_flaky = os.getenv('VTEST_FAIL_FLAKY') == '1'
48
49pub const test_only = os.getenv('VTEST_ONLY').split_any(',')
50
51pub const test_only_fn = os.getenv('VTEST_ONLY_FN').split_any(',')
52
53// TODO: this !!!*reliably*!!! fails compilation of `v cmd/tools/vbuild-examples.v` with a cgen error, without `-no-parallel`:
54// pub const fail_retry_delay_ms = os.getenv_opt('VTEST_FAIL_RETRY_DELAY_MS') or { '500' }.int() * time.millisecond
55// Note, it works with `-no-parallel`, and it works when that whole expr is inside a function, like below:
56pub const fail_retry_delay_ms = get_fail_retry_delay_ms()
57
58pub const pkgcmd = get_pkgcmd()
59
60pub const is_node_present = os.execute('node --version').exit_code == 0
61
62pub const is_go_present = os.execute('go version').exit_code == 0
63
64pub const is_ruby_present = os.execute('ruby --version').exit_code == 0
65 && os.execute('${pkgcmd} ruby --libs').exit_code == 0
66
67pub const is_python_present = os.execute('python --version').exit_code == 0
68 && os.execute('${pkgcmd} python3 --libs').exit_code == 0
69
70pub const is_sqlite3_present = get_present_sqlite()
71
72pub const all_processes = get_all_processes()
73
74pub const header_bytes_to_search_for_module_main = 500
75
76pub const separator = '-'.repeat(max_header_len) + '\n'
77
78pub const max_compilation_retries = get_max_compilation_retries()
79
80const c_error_bug_report_disabled_env = 'V_C_ERROR_BUG_REPORT_DISABLED'
81
82fn get_max_compilation_retries() int {
83 return os.getenv_opt('VTEST_MAX_COMPILATION_RETRIES') or { '3' }.int()
84}
85
86fn get_fail_retry_delay_ms() time.Duration {
87 return os.getenv_opt('VTEST_FAIL_RETRY_DELAY_MS') or { '500' }.int() * time.millisecond
88}
89
90fn get_pkgcmd() string {
91 for cmd in ['pkgconf', 'pkg-config'] {
92 if os.execute('${cmd} --version').exit_code == 0 {
93 return cmd
94 }
95 }
96 return 'false'
97}
98
99fn get_present_sqlite() bool {
100 if os.user_os() == 'windows' {
101 return os.exists(@VEXEROOT + '/thirdparty/sqlite/sqlite3.c')
102 }
103 return os.execute('sqlite3 --version').exit_code == 0
104 && os.execute('${pkgcmd} sqlite3 --libs').exit_code == 0
105}
106
107fn get_all_processes() []string {
108 $if windows {
109 // TODO
110 return []
111 } $else {
112 return os.execute('ps ax').output.split_any('\r\n')
113 }
114}
115
116pub enum ActionMode {
117 compile
118 compile_and_run
119}
120
121pub struct TestSession {
122pub mut:
123 files []string
124 skip_files []string
125 vexe string
126 vroot string
127 vtmp_dir string
128 vargs string
129 fail_fast bool
130 benchmark benchmark.Benchmark
131 rm_binaries bool = true
132 build_tools bool // builds only executables in cmd/tools; used by `v build-tools'
133 silent_mode bool
134 show_stats bool
135 show_asserts bool
136 progress_mode bool
137 root_relative bool // used by CI runs, so that the output is stable everywhere
138 nmessages chan LogMessage // many publishers, single consumer/printer
139 nmessage_idx int // currently printed message index
140 failed_cmds shared []string
141 reporter Reporter = Reporter(NormalReporter{})
142 hash string // used as part of the name of the temporary directory created for tests, to ease cleanup
143
144 exec_mode ActionMode = .compile // .compile_and_run only for `v test`
145
146 build_environment build_constraint.Environment // see the documentation in v.build_constraint
147 custom_defines []string // for adding custom defines, known only to the individual runners
148mut:
149 benchmark_mu &sync.Mutex = sync.new_mutex()
150}
151
152pub fn (mut ts TestSession) add_failed_cmd(cmd string) {
153 lock ts.failed_cmds {
154 ts.failed_cmds << cmd
155 }
156}
157
158fn (mut ts TestSession) benchmark_step() {
159 ts.benchmark_mu.lock()
160 defer {
161 ts.benchmark_mu.unlock()
162 }
163 ts.benchmark.step()
164}
165
166fn (mut ts TestSession) benchmark_step_restart() {
167 ts.benchmark_mu.lock()
168 defer {
169 ts.benchmark_mu.unlock()
170 }
171 ts.benchmark.step_restart()
172}
173
174fn (mut ts TestSession) benchmark_fail() {
175 ts.benchmark_mu.lock()
176 defer {
177 ts.benchmark_mu.unlock()
178 }
179 ts.benchmark.fail()
180}
181
182fn (mut ts TestSession) benchmark_ok() {
183 ts.benchmark_mu.lock()
184 defer {
185 ts.benchmark_mu.unlock()
186 }
187 ts.benchmark.ok()
188}
189
190fn (mut ts TestSession) benchmark_skip() {
191 ts.benchmark_mu.lock()
192 defer {
193 ts.benchmark_mu.unlock()
194 }
195 ts.benchmark.skip()
196}
197
198fn (mut ts TestSession) benchmark_stop() {
199 ts.benchmark_mu.lock()
200 defer {
201 ts.benchmark_mu.unlock()
202 }
203 ts.benchmark.stop()
204}
205
206pub fn (mut ts TestSession) show_list_of_failed_tests() {
207 rlock ts.failed_cmds {
208 ts.reporter.list_of_failed_commands(ts.failed_cmds)
209 }
210}
211
212struct MessageThreadContext {
213mut:
214 file string
215 flow_id string
216}
217
218fn (mut ts TestSession) append_message(kind MessageKind, msg string, mtc MessageThreadContext) {
219 ts.nmessages <- LogMessage{
220 file: mtc.file
221 flow_id: mtc.flow_id
222 message: msg
223 kind: kind
224 when: time.now()
225 }
226}
227
228fn (mut ts TestSession) append_message_with_duration(kind MessageKind, msg string, d time.Duration, mtc MessageThreadContext) {
229 ts.nmessages <- LogMessage{
230 file: mtc.file
231 flow_id: mtc.flow_id
232 message: msg
233 kind: kind
234 when: time.now()
235 took: d
236 }
237}
238
239pub fn (mut ts TestSession) session_start(message string) {
240 ts.reporter.session_start(message, mut ts)
241}
242
243pub fn (mut ts TestSession) session_stop(message string) {
244 ts.reporter.session_stop(message, mut ts)
245}
246
247pub fn (mut ts TestSession) print_messages() {
248 mut test_idx := 0
249 mut print_msg_time := time.new_stopwatch()
250 for {
251 // get a message from the channel of messages to be printed:
252 mut rmessage := <-ts.nmessages
253 ts.nmessage_idx++
254
255 // first sent *all events* to the output reporter, so it can then process them however it wants:
256 ts.reporter.report(ts.nmessage_idx, rmessage)
257
258 if rmessage.kind in [.cmd_begin, .cmd_end, .compile_begin] {
259 // The following events, are sent before the test framework has determined,
260 // what the full completion status is. They can also be repeated multiple times,
261 // for tests that are flaky and need repeating.
262 continue
263 }
264 if rmessage.kind == .compile_end {
265 if rmessage.message.trim_space().len == 0 {
266 continue
267 }
268 if ts.progress_mode {
269 ts.reporter.update_last_line_and_move_to_next(ts.nmessage_idx, '')
270 }
271 if rmessage.message.ends_with('\n') {
272 eprint(rmessage.message)
273 } else {
274 eprintln(rmessage.message)
275 }
276 continue
277 }
278 if rmessage.kind == .sentinel {
279 // a sentinel for stopping the printing thread
280 if !ts.silent_mode && ts.progress_mode {
281 ts.reporter.report_stop()
282 }
283 return
284 }
285 if rmessage.kind in [.stats_output, .stats_error] {
286 mut msg := rmessage.message
287 if msg != '' && !msg.ends_with('\n') {
288 msg += '\n'
289 }
290 if rmessage.kind == .stats_error {
291 eprint(msg)
292 flush_stderr()
293 } else {
294 print(msg)
295 flush_stdout()
296 }
297 continue
298 }
299 if rmessage.kind != .info {
300 // info events can also be repeated, and should be ignored when determining
301 // the total order of the current test file, in the following replacements:
302 test_idx++
303 }
304 msg := rmessage.message.replace_each([
305 'TMP1',
306 '${test_idx:1d}',
307 'TMP2',
308 '${test_idx:2d}',
309 'TMP3',
310 '${test_idx:3d}',
311 'TMP4',
312 '${test_idx:4d}',
313 ])
314 is_ok := rmessage.kind == .ok
315 //
316 time_passed := print_msg_time.elapsed().seconds()
317 if time_passed > 10 && ts.silent_mode && is_ok {
318 // Even if OK tests are suppressed,
319 // show *at least* 1 result every 10 seconds,
320 // otherwise the CI can seem stuck ...
321 ts.reporter.progress(ts.nmessage_idx, msg)
322 print_msg_time.restart()
323 continue
324 }
325 if ts.progress_mode {
326 if is_ok && !ts.silent_mode {
327 ts.reporter.update_last_line(ts.nmessage_idx, msg)
328 } else {
329 ts.reporter.update_last_line_and_move_to_next(ts.nmessage_idx, msg)
330 }
331 continue
332 }
333 if !ts.silent_mode || !is_ok {
334 // normal expanded mode, or failures in -silent mode
335 ts.reporter.message(ts.nmessage_idx, msg)
336 continue
337 }
338 }
339}
340
341pub fn (mut ts TestSession) execute(cmd string, mtc MessageThreadContext) os.Result {
342 if show_cmd {
343 ts.append_message(.info, '> execute cmd: ${cmd}', mtc)
344 }
345 return os.execute(cmd)
346}
347
348pub fn (mut ts TestSession) system(cmd string, mtc MessageThreadContext) int {
349 if show_cmd {
350 ts.append_message(.info, '> system cmd: ${cmd}', mtc)
351 }
352 return os.system(cmd)
353}
354
355pub fn new_test_session(_vargs string, will_compile bool) TestSession {
356 os.setenv(c_error_bug_report_disabled_env, '1', true)
357 mut skip_files := []string{}
358 vexe := pref.vexe_path()
359 vroot := os.dir(vexe)
360 if will_compile {
361 if runner_os != 'Linux' || !github_job.starts_with('tcc-') {
362 if !os.exists('/usr/local/include/wkhtmltox/pdf.h') {
363 skip_files << 'examples/c_interop_wkhtmltopdf.v' // needs installation of wkhtmltopdf from https://github.com/wkhtmltopdf/packaging/releases
364 }
365 }
366 }
367 if os.user_os() == 'windows' {
368 skip_files << windows_disabled_fasthttp_veb_tests(vroot)
369 }
370 skip_files = skip_files.map(os.abs_path)
371 vargs := _vargs.replace('-progress', '')
372 hash := '${sync.thread_id().hex()}_${rand.ulid()}'
373 new_vtmp_dir := setup_new_vtmp_folder(hash)
374 if term.can_show_color_on_stderr() {
375 os.setenv('VCOLORS', 'always', true)
376 }
377 mut ts := TestSession{
378 vexe: vexe
379 vroot: vroot
380 skip_files: skip_files
381 fail_fast: fail_fast
382 show_stats: '-stats' in vargs.split(' ')
383 show_asserts: '-show-asserts' in vargs.split(' ')
384 vargs: vargs
385 vtmp_dir: new_vtmp_dir
386 hash: hash
387 silent_mode: _vargs.contains('-silent')
388 progress_mode: _vargs.contains('-progress')
389 }
390 if keep_session {
391 ts.rm_binaries = false
392 println('> vtmp_dir: ${new_vtmp_dir}')
393 }
394
395 ts.handle_test_runner_option()
396 return ts
397}
398
399fn windows_disabled_fasthttp_veb_tests(vroot string) []string {
400 mut files := []string{}
401 for dir in [
402 os.join_path(vroot, 'vlib', 'fasthttp'),
403 os.join_path(vroot, 'vlib', 'veb'),
404 ] {
405 if !os.is_dir(dir) {
406 continue
407 }
408 os.walk(dir, fn [mut files] (path string) {
409 if path.ends_with('_test.v') || path.ends_with('_test.c.v')
410 || path.ends_with('_test.js.v') {
411 files << path
412 }
413 })
414 }
415 session_app_test := os.join_path(vroot, 'vlib', 'x', 'sessions', 'tests', 'session_app_test.v')
416 if os.exists(session_app_test) {
417 files << session_app_test
418 }
419 return files
420}
421
422fn (mut ts TestSession) handle_test_runner_option() {
423 test_runner := cmdline.option(os.args, '-test-runner', 'normal')
424 if test_runner !in pref.supported_test_runners {
425 eprintln('v test: `-test-runner ${test_runner}` is not using one of the supported test runners: ${pref.supported_test_runners_list()}')
426 }
427 test_runner_implementation_file := os.join_path(ts.vroot,
428 'cmd/tools/modules/testing/output_${test_runner}.v')
429 if !os.exists(test_runner_implementation_file) {
430 eprintln('v test: using `-test-runner ${test_runner}` needs ${test_runner_implementation_file} to exist, and contain a valid testing.Reporter implementation for that runner. See `cmd/tools/modules/testing/output_dump.v` for an example.')
431 exit(1)
432 }
433 match test_runner {
434 'normal' {
435 // default, nothing to do
436 }
437 'dump' {
438 ts.reporter = DumpReporter{}
439 }
440 'teamcity' {
441 ts.reporter = TeamcityReporter{}
442 }
443 else {
444 dump('just set ts.reporter to an instance of your own struct here')
445 }
446 }
447}
448
449pub fn (mut ts TestSession) init() {
450 ts.files.sort()
451 ts.benchmark = benchmark.new_benchmark_no_cstep()
452}
453
454pub fn (mut ts TestSession) add(file string) {
455 ts.files << file
456}
457
458pub fn (mut ts TestSession) test() {
459 unbuffer_stdout()
460 // Ensure that .tmp.c files generated from compiling _test.v files,
461 // are easy to delete at the end, *without* affecting the existing ones.
462 current_wd := os.getwd()
463 if current_wd == os.wd_at_startup && current_wd == ts.vroot {
464 ts.root_relative = true
465 }
466
467 ts.init()
468 mut remaining_files := []string{}
469 for dot_relative_file in ts.files {
470 file := os.real_path(dot_relative_file)
471 if ts.build_tools && dot_relative_file.ends_with('_test.v') {
472 continue
473 }
474 // Skip OS-specific tests if we are not running that OS
475 // Special case for android_outside_termux because of its
476 // underscores
477 if file.ends_with('_android_outside_termux_test.v') {
478 if !host_os.is_target_of('android_outside_termux') {
479 remaining_files << dot_relative_file
480 ts.skip_files << file
481 continue
482 }
483 }
484 os_target := file.all_before_last('_test.v').all_after_last('_')
485 if !host_os.is_target_of(os_target) {
486 remaining_files << dot_relative_file
487 ts.skip_files << file
488 continue
489 }
490 remaining_files << dot_relative_file
491 }
492 remaining_files = vtest.filter_vtest_only(remaining_files, fix_slashes: false)
493 ts.files = remaining_files
494 ts.benchmark.set_total_expected_steps(remaining_files.len)
495 mut njobs := runtime.nr_jobs()
496 if remaining_files.len < njobs {
497 njobs = remaining_files.len
498 }
499 ts.benchmark.njobs = njobs
500 mut pool_of_test_runners := pool.new_pool_processor(callback: worker_trunner)
501 // ensure that the nmessages queue/channel, has enough capacity for handling many messages across threads, without blocking
502 ts.nmessages = chan LogMessage{cap: 10000}
503 ts.nmessage_idx = 0
504 printing_thread := spawn ts.print_messages()
505 pool_of_test_runners.set_shared_context(ts)
506 ts.reporter.worker_threads_start(remaining_files, mut ts)
507
508 ts.setup_build_environment()
509
510 // all the testing happens here:
511 pool_of_test_runners.work_on_pointers(unsafe { remaining_files.pointers() })
512
513 ts.benchmark_stop()
514 ts.append_message(.sentinel, '', MessageThreadContext{ flow_id: '-1' }) // send the sentinel
515 printing_thread.wait()
516 ts.reporter.worker_threads_finish(mut ts)
517 ts.reporter.divider()
518 ts.show_list_of_failed_tests()
519
520 // cleanup the session folder, if everything was ok:
521 if ts.benchmark.nfail == 0 {
522 if ts.rm_binaries {
523 os.rmdir_all(ts.vtmp_dir) or {}
524 }
525 }
526 if os.ls(ts.vtmp_dir) or { [] }.len == 0 {
527 os.rmdir_all(ts.vtmp_dir) or {}
528 }
529}
530
531fn worker_trunner(mut p pool.PoolProcessor, idx int, thread_id int) voidptr {
532 mut ts := unsafe { &TestSession(p.get_shared_context()) }
533 if ts.fail_fast {
534 if ts.failed_cmds.len > 0 {
535 return pool.no_result
536 }
537 }
538 // tls_bench is used to format the step messages/timings
539 mut tls_bench := unsafe { &benchmark.Benchmark(p.get_thread_context(idx)) }
540 if isnil(tls_bench) {
541 tls_bench = benchmark.new_benchmark_pointer()
542 tls_bench.set_total_expected_steps(ts.benchmark.nexpected_steps)
543 p.set_thread_context(idx, tls_bench)
544 }
545 tls_bench.no_cstep = true
546 tls_bench.njobs = ts.benchmark.njobs
547 abs_path := os.real_path(p.get_item[string](idx))
548 mut relative_file := abs_path
549 mut cmd_options :=
550 vflags.tokenize_to_args(ts.vargs) // make sure that `'-W -silent'` becomes `['-W', '-silent']`, while keeping quoted spaces intact
551 mut run_js := false
552
553 is_fmt := ts.vargs.contains('fmt')
554 is_vet := ts.vargs.contains('vet')
555 produces_file_output := !(is_fmt || is_vet)
556
557 if relative_file.ends_with('.js.v') {
558 if produces_file_output {
559 cmd_options << ' -b js'
560 run_js = true
561 }
562 }
563
564 if relative_file.ends_with('.c.v') {
565 if produces_file_output {
566 cmd_options << ' -b c'
567 run_js = false
568 }
569 }
570
571 if relative_file.contains('global') && !is_fmt {
572 cmd_options << ' -enable-globals'
573 }
574 if ts.root_relative {
575 relative_file = relative_file.replace_once(ts.vroot + os.path_separator, '')
576 }
577 normalised_relative_file := relative_file.replace('\\', '/')
578
579 file := abs_path
580 mtc := MessageThreadContext{
581 file: file
582 flow_id: thread_id.str()
583 }
584
585 // Ensure that the generated binaries will be stored in an *unique*, fresh, and per test folder,
586 // inside the common session temporary folder, used for all the tests.
587 // This is done to provide a clean working environment, for each test, that will not contain
588 // files from other tests, and will make sure that tests with the same name, can be compiled
589 // inside their own folders, without name conflicts (and without locking issues on windows,
590 // where an executable is not writable, if it is running).
591 // Note, that the common session temporary folder ts.vtmp_dir,
592 // will be removed after all tests are done.
593 test_id := '${idx}_${thread_id}'
594 mut test_folder_path := os.join_path(ts.vtmp_dir, test_id)
595 if ts.build_tools {
596 // `v build-tools`, produce all executables in the same session folder, so that they can be copied later:
597 test_folder_path = ts.vtmp_dir
598 } else {
599 os.mkdir_all(test_folder_path) or {}
600 }
601 fname := os.file_name(file)
602 // There are test files ending with `_test.v`, `_test.c.v` and `_test.js.v`.
603 mut fname_without_extension := fname.all_before_last('.v')
604 if fname_without_extension.ends_with('.c') {
605 fname_without_extension = fname_without_extension.all_before_last('.c')
606 }
607 generated_binary_fname := if os.user_os() == 'windows' && !run_js {
608 fname_without_extension + '.exe'
609 } else {
610 fname_without_extension
611 }
612 mut details := get_test_details(file)
613 if details.vflags != '' && !is_fmt {
614 cmd_options << details.vflags
615 }
616
617 reproduce_options := cmd_options.clone()
618 generated_binary_fpath := os.join_path_single(test_folder_path, generated_binary_fname)
619 if produces_file_output {
620 if ts.rm_binaries {
621 os.rm(generated_binary_fpath) or {}
622 }
623 cmd_options << ' -o ${os.quoted_path(generated_binary_fpath)}'
624 }
625 defer {
626 if produces_file_output && ts.rm_binaries {
627 os.rmdir_all(test_folder_path) or {}
628 }
629 }
630
631 mut skip_running := '-skip-running'
632 if ts.show_stats {
633 skip_running = ''
634 }
635 compile_options := cmd_options.filter(it != '-silent')
636 mut compile_vexe := ts.vexe
637 mut compile_args := '${skip_running} ${compile_options.join(' ')}'
638 mut reproduce_vexe := ts.vexe
639 mut reproduce_args := reproduce_options.join(' ')
640 // `_test.vv2` files are v2-only integration tests: full V programs that
641 // exercise v2-specific syntax. Compile them with the v2 binary instead of
642 // v1, forwarding only flags that v2 recognizes — v2 errors on unknown
643 // flags, so v1-specific options must be stripped. Preserving `-d <name>`,
644 // `-b`/`-backend`, `-cc`, `-stats`, etc. keeps `v test -d feature ...`
645 // and per-file `// vtest vflags` working for conditional code paths.
646 is_vv2 := relative_file.ends_with('_test.vv2')
647 if is_vv2 {
648 mut v2_bin := os.join_path(ts.vroot, 'cmd', 'v2', 'v2')
649 $if windows {
650 v2_bin += '.exe'
651 }
652 if !os.is_executable(v2_bin) {
653 ts.append_message(.info, 'SKIP ${relative_file}: v2 binary not built. Run: ${os.quoted_path(ts.vexe)} -o ${os.quoted_path(v2_bin)} ${os.quoted_path(os.join_path(ts.vroot,
654 'cmd', 'v2', 'v2.v'))}', mtc)
655 ts.benchmark_skip()
656 tls_bench.skip()
657 return pool.no_result
658 }
659 compile_vexe = v2_bin
660 compile_args = filter_args_for_v2(compile_options)
661 // Reproduction command must invoke v2 too, otherwise the suggested
662 // rerun fails immediately on v2-only syntax.
663 reproduce_vexe = v2_bin
664 reproduce_args = filter_args_for_v2(reproduce_options)
665 }
666 reproduce_cmd := '${os.quoted_path(reproduce_vexe)} ${reproduce_args} ${os.quoted_path(file)}'
667 cmd := '${os.quoted_path(compile_vexe)} ${compile_args} ${os.quoted_path(file)}'
668 run_cmd := if run_js {
669 'node ${os.quoted_path(generated_binary_fpath)}'
670 } else {
671 os.quoted_path(generated_binary_fpath)
672 }
673 mut should_be_built := true
674 if details.vbuild != '' {
675 should_be_built = ts.build_environment.eval(details.vbuild) or {
676 eprintln('${file}:${details.vbuild_line}:17: error during parsing the `// v test build` expression `${details.vbuild}`: ${err}')
677 false
678 }
679 $if trace_should_be_built ? {
680 eprintln('${file} has specific build constraint: `${details.vbuild}` => should_be_built: `${should_be_built}`')
681 eprintln('> env facts: ${ts.build_environment.facts}')
682 eprintln('> env defines: ${ts.build_environment.defines}')
683 }
684 }
685
686 ts.benchmark_step()
687 tls_bench.step()
688 if produces_file_output && !ts.build_tools && (!should_be_built || abs_path in ts.skip_files) {
689 ts.benchmark_skip()
690 tls_bench.skip()
691 if !hide_skips {
692 ts.append_message(.skip, tls_bench.step_message_with_label_and_duration(benchmark.b_skip,
693 normalised_relative_file, 0,
694 preparation: 1 * time.microsecond
695 ), mtc)
696 }
697 return pool.no_result
698 }
699 mut compile_cmd_duration := time.Duration(0)
700 mut cmd_duration := time.Duration(0)
701 if ts.show_stats {
702 ts.append_message(.cmd_begin, cmd, mtc)
703 d_cmd := time.new_stopwatch()
704 mut res := ts.execute(cmd, mtc)
705 mut status := res.exit_code
706 if res.output != '' {
707 output_kind := if status == 0 { MessageKind.stats_output } else { .stats_error }
708 ts.append_message(output_kind, res.output, mtc)
709 }
710
711 cmd_duration = d_cmd.elapsed()
712 ts.append_message_with_duration(.cmd_end, '', cmd_duration, mtc)
713
714 if status != 0 {
715 os.setenv('VTEST_RETRY_MAX', '${details.retry}', true)
716 for retry := 1; retry <= details.retry; retry++ {
717 if !details.hide_retries {
718 ts.append_message(.info,
719 ' [stats] retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
720 mtc)
721 }
722 os.setenv('VTEST_RETRY', '${retry}', true)
723 ts.append_message(.cmd_begin, cmd, mtc)
724 d_cmd_2 := time.new_stopwatch()
725 retry_res := ts.execute(cmd, mtc)
726 status = retry_res.exit_code
727 if retry_res.output != '' {
728 output_kind := if status == 0 { MessageKind.stats_output } else { .stats_error }
729 ts.append_message(output_kind, retry_res.output, mtc)
730 }
731 cmd_duration = d_cmd_2.elapsed()
732 ts.append_message_with_duration(.cmd_end, '', cmd_duration, mtc)
733
734 if status == 0 {
735 unsafe {
736 goto test_passed_system
737 }
738 }
739 time.sleep(fail_retry_delay_ms)
740 }
741 if details.flaky && !fail_flaky {
742 ts.append_message(.info,
743 ' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\ncmd: ${cmd}',
744 mtc)
745 unsafe {
746 goto test_passed_system
747 }
748 }
749 // most probably compiler error
750 if res.output.contains(': error: ') {
751 ts.append_message(.cannot_compile, 'Cannot compile file ${file}', mtc)
752 }
753 ts.benchmark_fail()
754 tls_bench.fail()
755 ts.add_failed_cmd(reproduce_cmd)
756 return pool.no_result
757 }
758 } else {
759 if show_start {
760 ts.append_message(.info, ' starting ${relative_file} ...', mtc)
761 }
762 ts.append_message(.compile_begin, cmd, mtc)
763 compile_d_cmd := time.new_stopwatch()
764 mut compile_r := os.Result{}
765 for cretry in 0 .. max_compilation_retries {
766 compile_r = ts.execute(cmd, mtc)
767 compile_cmd_duration = compile_d_cmd.elapsed()
768 // eprintln('>>>> cretry: ${cretry} | compile_r.exit_code: ${compile_r.exit_code} | compile_cmd_duration: ${compile_cmd_duration:8} | file: ${normalised_relative_file}')
769 if compile_r.exit_code == 0 {
770 break
771 }
772 random_sleep_ms(50, 100 * cretry)
773 }
774 ts.append_message_with_duration(.compile_end, compile_r.output, compile_cmd_duration, mtc)
775 if compile_r.exit_code != 0 {
776 ts.benchmark_fail()
777 tls_bench.fail()
778 ts.append_message_with_duration(.fail, tls_bench.step_message_with_label_and_duration(benchmark.b_fail,
779 '${normalised_relative_file}\n>> compilation failed:\n${compile_r.output}',
780 cmd_duration,
781 preparation: compile_cmd_duration
782 ), cmd_duration, mtc)
783 ts.add_failed_cmd(reproduce_cmd)
784 return pool.no_result
785 }
786 tls_bench.step_restart()
787 ts.benchmark_step_restart()
788 if ts.exec_mode == .compile {
789 unsafe {
790 goto test_passed_execute
791 }
792 }
793 //
794 mut retry := 1
795 mut failure_output := strings.new_builder(1024)
796 ts.append_message(.cmd_begin, run_cmd, mtc)
797 d_cmd := time.new_stopwatch()
798 mut r := ts.execute(run_cmd, mtc)
799 cmd_duration = d_cmd.elapsed()
800 ts.append_message_with_duration(.cmd_end, r.output, cmd_duration, mtc)
801 if ts.show_asserts && r.exit_code == 0 {
802 println(r.output.split_into_lines().filter(it.contains(' assert')).join('\n'))
803 }
804 if r.exit_code != 0 {
805 mut trimmed_output := r.output.trim_space()
806 if trimmed_output.len == 0 {
807 // retry running at least 1 more time, to avoid CI false positives as much as possible
808 details.retry++
809 }
810 if details.retry != 0 {
811 failure_output.write_string(separator)
812 failure_output.writeln(' retry: 0 ; max_retry: ${details.retry} ; r.exit_code: ${r.exit_code} ; trimmed_output.len: ${trimmed_output.len}')
813 }
814 failure_output.writeln(trimmed_output)
815 os.setenv('VTEST_RETRY_MAX', '${details.retry}', true)
816 for retry = 1; retry <= details.retry; retry++ {
817 if !details.hide_retries {
818 ts.append_message(.info,
819 ' retrying ${retry}/${details.retry} of ${relative_file} ; known flaky: ${details.flaky} ...',
820 mtc)
821 }
822 os.setenv('VTEST_RETRY', '${retry}', true)
823 ts.append_message(.cmd_begin, run_cmd, mtc)
824 d_cmd_2 := time.new_stopwatch()
825 r = ts.execute(run_cmd, mtc)
826 cmd_duration = d_cmd_2.elapsed()
827 ts.append_message_with_duration(.cmd_end, r.output, cmd_duration, mtc)
828
829 if r.exit_code == 0 {
830 unsafe {
831 goto test_passed_execute
832 }
833 }
834 trimmed_output = r.output.trim_space()
835 failure_output.write_string(separator)
836 failure_output.writeln(' retry: ${retry} ; max_retry: ${details.retry} ; r.exit_code: ${r.exit_code} ; trimmed_output.len: ${trimmed_output.len}')
837 failure_output.writeln(trimmed_output)
838 time.sleep(fail_retry_delay_ms)
839 }
840 full_failure_output := failure_output.str().trim_space()
841 if details.flaky && !fail_flaky {
842 ts.append_message(.info, '>>> flaky failures so far:', mtc)
843 for line in full_failure_output.split_into_lines() {
844 ts.append_message(.info, '>>>>>> ${line}', mtc)
845 }
846 ts.append_message(.info,
847 ' *FAILURE* of the known flaky test file ${relative_file} is ignored, since VTEST_FAIL_FLAKY is 0 . Retry count: ${details.retry} .\n comp_cmd: ${cmd}\n run_cmd: ${run_cmd}',
848 mtc)
849 unsafe {
850 goto test_passed_execute
851 }
852 }
853 ts.benchmark_fail()
854 tls_bench.fail()
855 cmd_duration = d_cmd.elapsed() - (fail_retry_delay_ms * details.retry)
856 ts.append_message_with_duration(.fail, tls_bench.step_message_with_label_and_duration(benchmark.b_fail,
857 '${normalised_relative_file}\n${full_failure_output}', cmd_duration,
858 preparation: compile_cmd_duration
859 ), cmd_duration, mtc)
860 ts.add_failed_cmd(reproduce_cmd)
861 return pool.no_result
862 }
863 }
864 test_passed_system:
865 test_passed_execute:
866 ts.benchmark_ok()
867 tls_bench.ok()
868 if !hide_oks {
869 ts.append_message_with_duration(.ok, tls_bench.step_message_with_label_and_duration(benchmark.b_ok,
870 normalised_relative_file, cmd_duration,
871 preparation: compile_cmd_duration
872 ), cmd_duration, mtc)
873 }
874 return pool.no_result
875}
876
877pub fn vlib_should_be_present(parent_dir string) {
878 vlib_dir := os.join_path_single(parent_dir, 'vlib')
879 if !os.is_dir(vlib_dir) {
880 eprintln('${vlib_dir} is missing, it must be next to the V executable')
881 exit(1)
882 }
883}
884
885pub fn prepare_test_session(zargs string, folder string, oskipped []string, main_label string) TestSession {
886 vexe := pref.vexe_path()
887 parent_dir := os.dir(vexe)
888 nparent_dir := parent_dir.replace('\\', '/')
889 vlib_should_be_present(parent_dir)
890 vargs := zargs.replace(vexe, '')
891 eheader(main_label)
892 if vargs.len > 0 {
893 eprintln('v compiler args: "${vargs}"')
894 }
895 mut session := new_test_session(vargs, true)
896 files := os.walk_ext(os.join_path_single(parent_dir, folder), '.v')
897 mut mains := []string{}
898 mut skipped := oskipped.clone()
899 next_file: for f in files {
900 fnormalised := f.replace('\\', '/')
901 // Note: a `testdata` folder, is the preferred name of a folder, containing V code,
902 // that you *do not want* the test framework to find incidentally for various reasons,
903 // for example module import tests, or subtests, that are compiled/run by other parent tests
904 // in specific configurations, etc.
905 if fnormalised.contains('testdata/') || fnormalised.contains('modules/')
906 || fnormalised.contains('preludes/') {
907 continue
908 }
909 $if windows {
910 // skip process/command examples on windows. TODO: remove the need for this, fix os.Command
911 if fnormalised.ends_with('examples/process/command.v') {
912 skipped << fnormalised.replace(nparent_dir + '/', '')
913 continue
914 }
915 }
916 c := os.read_file(fnormalised) or { panic(err) }
917 start := c#[0..header_bytes_to_search_for_module_main]
918 if start.contains('module ') {
919 modname := start.all_after('module ').all_before('\n')
920 if modname !in ['main', 'no_main'] {
921 skipped << fnormalised.replace(nparent_dir + '/', '')
922 continue next_file
923 }
924 }
925 for skip_prefix in oskipped {
926 skip_folder := skip_prefix + '/'
927 if fnormalised.starts_with(skip_folder) {
928 continue next_file
929 }
930 }
931 mains << fnormalised
932 }
933 session.files << mains
934 session.skip_files << skipped
935 return session
936}
937
938pub type FnTestSetupCb = fn (mut session TestSession)
939
940pub fn v_build_failing_skipped(zargs string, folder string, oskipped []string, cb FnTestSetupCb) bool {
941 main_label := 'Building ${folder} ...'
942 finish_label := 'building ${folder}'
943 mut session := prepare_test_session(zargs, folder, oskipped, main_label)
944 cb(mut session)
945 session.test()
946 eprintln(session.benchmark.total_message(finish_label))
947 return session.failed_cmds.len > 0
948}
949
950pub fn build_v_cmd_failed(cmd string) bool {
951 res := os.execute(cmd)
952 if res.exit_code < 0 {
953 return true
954 }
955 if res.exit_code != 0 {
956 eprintln('')
957 eprintln(res.output)
958 return true
959 }
960 return false
961}
962
963pub fn building_any_v_binaries_failed() bool {
964 eheader('Building V binaries...')
965 eprintln('VFLAGS is: "' + os.getenv('VFLAGS') + '"')
966 vexe := pref.vexe_path()
967 parent_dir := os.dir(vexe)
968 vlib_should_be_present(parent_dir)
969 os.chdir(parent_dir) or { panic(err) }
970 mut failed := false
971 v_build_commands := ['${vexe} -o v_g -g cmd/v',
972 '${vexe} -o v_prod_g -prod -g cmd/v', '${vexe} -o v_cg -cg cmd/v',
973 '${vexe} -o v_prod_cg -prod -cg cmd/v', '${vexe} -o v_prod -prod cmd/v']
974 mut bmark := benchmark.new_benchmark()
975 for cmd in v_build_commands {
976 bmark.step()
977 if build_v_cmd_failed(cmd) {
978 bmark.fail()
979 failed = true
980 eprintln(bmark.step_message_fail('command: ${cmd} . See details above ^^^^^^^'))
981 eprintln('')
982 continue
983 }
984 bmark.ok()
985 if !hide_oks {
986 eprintln(bmark.step_message_ok('command: ${cmd}'))
987 }
988 }
989 bmark.stop()
990 h_divider()
991 eprintln(bmark.total_message('building v binaries'))
992 return failed
993}
994
995pub fn h_divider() {
996 eprintln(term.h_divider('-')#[..max_header_len])
997}
998
999// filter_args_for_v2 returns a command-line string containing only the flags
1000// the v2 compiler accepts (`vlib/v2_toberemoved/pref/pref.v`). v2 errors on any unknown
1001// flag, so this is used when forwarding `v test` options to v2 for
1002// `_test.vv2` files. Keep these lists in sync with v2's pref validator.
1003fn filter_args_for_v2(compile_options []string) string {
1004 v2_value_flags := ['-backend', '-b', '-o', '-output', '-arch', '-printfn', '-gc', '-d', '-hot-fn',
1005 '-cc']
1006 v2_bool_flags := ['--debug', '--verbose', '-v', '--skip-genv', '--skip-builtin', '--skip-imports',
1007 '--skip-type-check', '--no-parallel', '-nocache', '--nocache', '-nomarkused', '--nomarkused',
1008 '-showcc', '--showcc', '-stats', '--stats', '-print-parsed-files', '--print-parsed-files',
1009 '-keepc', '--profile-alloc', '-profile-alloc', '-enable-globals', '--enable-globals',
1010 '-shared', '--shared', '-O0', '--single-backend', '-single-backend', '-prod', '-prealloc',
1011 '-ownership']
1012 tokens := vflags.tokenize_to_args(compile_options.join(' '))
1013 mut out := []string{}
1014 mut i := 0
1015 for i < tokens.len {
1016 t := tokens[i]
1017 if t in v2_value_flags {
1018 if i + 1 < tokens.len {
1019 out << t
1020 out << os.quoted_path(tokens[i + 1])
1021 i += 2
1022 continue
1023 }
1024 } else if t in v2_bool_flags {
1025 out << t
1026 }
1027 i++
1028 }
1029 return out.join(' ')
1030}
1031
1032// setup_new_vtmp_folder creates a new nested folder inside VTMP, then resets VTMP to it,
1033// so that V programs/tests will write their temporary files to new location.
1034// The new nested folder, and its contents, will get removed after all tests/programs succeed.
1035pub fn setup_new_vtmp_folder(hash string) string {
1036 new_vtmp_dir := os.join_path(os.vtmp_dir(), 'tsession_${hash}')
1037 os.mkdir_all(new_vtmp_dir) or { panic(err) }
1038 os.setenv('VTMP', new_vtmp_dir, true)
1039 return new_vtmp_dir
1040}
1041
1042pub struct TestDetails {
1043pub mut:
1044 retry int
1045 flaky bool // when flaky tests fail, the whole run is still considered successful, unless VTEST_FAIL_FLAKY is 1
1046 //
1047 hide_retries bool // when true, all retry tries are silent; used by `vlib/v/tests/retry_test.v`
1048 vbuild string // could be `!(windows && tinyc)`
1049 vbuild_line int // for more precise error reporting, if the `vbuild` expression is incorrect
1050 vflags string // custom compilation flags for the test (enables for example: `// vtest vflags: -w`, for tests that have known warnings, but should still pass with -W)
1051}
1052
1053pub fn get_test_details(file string) TestDetails {
1054 mut res := TestDetails{}
1055 if !os.is_file(file) {
1056 return res
1057 }
1058 lines := os.read_lines(file) or { [] }
1059 for idx, line in lines {
1060 if line.starts_with('// vtest retry:') {
1061 res.retry = line.all_after(':').trim_space().int()
1062 }
1063 if line.starts_with('// vtest flaky:') {
1064 res.flaky = line.all_after(':').trim_space().bool()
1065 }
1066 if line.starts_with('// vtest build:') {
1067 res.vbuild = line.all_after(':').trim_space()
1068 res.vbuild_line = idx + 1
1069 }
1070 if line.starts_with('// vtest vflags:') {
1071 res.vflags = line.all_after(':').trim_space()
1072 }
1073 if line.starts_with('// vtest hide_retries') {
1074 res.hide_retries = true
1075 }
1076 }
1077 return res
1078}
1079
1080pub fn find_started_process(pname string) !string {
1081 for line in all_processes {
1082 if line.contains(pname) {
1083 return line
1084 }
1085 }
1086 return error('could not find process matching ${pname}')
1087}
1088
1089fn limited_header(msg string) string {
1090 return term.header_left(msg, '-')#[..max_header_len]
1091}
1092
1093pub fn eheader(msg string) {
1094 eprintln(limited_header(msg))
1095}
1096
1097pub fn header(msg string) {
1098 println(limited_header(msg))
1099 flush_stdout()
1100}
1101
1102fn random_sleep_ms(_ int, _ int) {
1103 time.sleep((50 + rand.intn(50) or { 0 }) * time.millisecond)
1104}
1105
1106fn get_max_header_len() int {
1107 maximum := 140
1108 cols, _ := term.get_terminal_size()
1109 if cols > maximum {
1110 return maximum
1111 }
1112 return cols
1113}
1114
1115fn check_openssl_present() bool {
1116 if github_job.ends_with('-windows') {
1117 // TODO: investigate the https://github.com/vlang/v/actions/runs/18590919000/job/53005499130 failure in more details
1118 return false
1119 }
1120 $if openbsd {
1121 return os.execute('eopenssl35 --version').exit_code == 0
1122 && os.execute('${pkgcmd} eopenssl35 --libs').exit_code == 0
1123 } $else {
1124 return os.execute('openssl --version').exit_code == 0
1125 && os.execute('${pkgcmd} openssl --libs').exit_code == 0
1126 }
1127}
1128
1129fn check_modern_openssl_present() bool {
1130 if !is_openssl_present {
1131 return false
1132 }
1133 mut version_cmd := 'openssl version'
1134 $if openbsd {
1135 version_cmd = 'eopenssl35 version'
1136 }
1137 res := os.execute(version_cmd)
1138 if res.exit_code != 0 {
1139 return false
1140 }
1141 line := res.output.trim_space()
1142 if !line.starts_with('OpenSSL ') {
1143 return false
1144 }
1145 version := semver.coerce(line) or { return false }
1146 return version.satisfies('>=3.5.0')
1147}
1148
1149pub const is_openssl_present = check_openssl_present()
1150pub const is_modern_openssl_present = check_modern_openssl_present()
1151
1152// is_started_mysqld is true, when the test runner determines that there is a running mysql server
1153pub const is_started_mysqld = find_started_process('mysqld') or { '' }
1154
1155// is_started_postgres is true, when the test runner determines that there is a running postgres server
1156pub const is_started_postgres = find_started_process('postgres') or { '' }
1157
1158// is_started_mssql is true, when the test runner determines that there is a running sql server
1159pub const is_started_mssql = find_started_process('sqlservr') or { '' }
1160
1161// is_started_redis is true, when the test runner determines that there is a running redis server
1162pub const is_started_redis = find_started_process('redis-server') or { '' }
1163
1164pub fn (mut ts TestSession) setup_build_environment() {
1165 facts, mut defines := pref.get_build_facts_and_defines()
1166 // add the runtime information, that the test runner has already determined by checking once:
1167 if github_job.starts_with('sanitize-') {
1168 defines << 'sanitized_job'
1169 }
1170 if is_started_mysqld != '' {
1171 defines << 'started_mysqld'
1172 }
1173 if is_started_postgres != '' {
1174 defines << 'started_postgres'
1175 }
1176 if is_started_mssql != '' {
1177 defines << 'started_mssql'
1178 }
1179 if is_started_redis != '' {
1180 defines << 'started_redis'
1181 }
1182 if is_node_present {
1183 defines << 'present_node'
1184 }
1185 if is_python_present {
1186 defines << 'present_python'
1187 }
1188 if is_ruby_present {
1189 defines << 'present_ruby'
1190 }
1191 if is_go_present {
1192 defines << 'present_go'
1193 }
1194 if is_sqlite3_present {
1195 defines << 'present_sqlite3'
1196 }
1197 if is_openssl_present {
1198 defines << 'present_openssl'
1199 }
1200 if is_modern_openssl_present {
1201 defines << 'has_modern_openssl'
1202 }
1203
1204 // detect the linux distribution as well when possible:
1205 if os.is_file('/etc/os-release') {
1206 mut distro_kind := ''
1207 if lines := os.read_lines('/etc/os-release') {
1208 for line in lines {
1209 if line.starts_with('ID=') {
1210 distro_kind = line.all_after('ID=')
1211 break
1212 }
1213 }
1214 }
1215 if distro_kind != '' {
1216 defines << 'os_id_${distro_kind}' // os_id_alpine, os_id_freebsd, os_id_ubuntu, os_id_debian etc
1217 }
1218 }
1219
1220 defines << ts.custom_defines
1221 $if trace_vbuild ? {
1222 eprintln('>>> testing.get_build_environment facts: ${facts}')
1223 eprintln('>>> testing.get_build_environment defines: ${defines}')
1224 }
1225 ts.build_environment = build_constraint.new_environment(facts, defines)
1226}
1227