v2 / vlib / v / debug / tests / trace / trace_test.v
65 lines · 55 sloc · 1.23 KB · 152a97786568c09917641ef7a631714a059f46ef
Raw
1@[has_globals]
2module main
3
4import time
5import v.debug
6
7__global counter = HookCounter{}
8
9struct HookCounter {
10pub mut:
11 after int
12 before int
13}
14
15@[heap]
16struct Profiler {
17mut:
18 fn_map map[string]time.StopWatch
19}
20
21fn (mut p Profiler) trace_after(fn_name string) {
22 counter.after++
23 println('>>> called after ${fn_name} - ${p.fn_map[fn_name].elapsed()}')
24}
25
26fn (mut p Profiler) trace_before(fn_name string) {
27 p.fn_map[fn_name] = time.new_stopwatch()
28 println('>>> called before ${fn_name}')
29 counter.before++
30}
31
32fn test_call() {
33 println('${@FN} got called')
34 time.sleep(100)
35}
36
37fn hook_before(fn_name string) {
38 counter.before++
39}
40
41fn hook_after(fn_name string) {
42 counter.after++
43}
44
45fn test_main() {
46 counter = HookCounter{}
47 mut myprofiler := Profiler{}
48 hook1 := debug.add_after_call(myprofiler.trace_after)
49 hook2 := debug.add_before_call(myprofiler.trace_before)
50 hook3 := debug.add_before_call(hook_before)
51 hook4 := debug.add_after_call(hook_after)
52 test_call()
53 debug.remove_after_call(hook1)
54 debug.remove_before_call(hook2)
55 debug.remove_before_call(hook3)
56 debug.remove_after_call(hook4)
57 test_call()
58 $if trace ? {
59 assert counter.before == 4
60 assert counter.after == 4
61 } $else {
62 assert counter.before == 0
63 assert counter.after == 0
64 }
65}
66