@@ -19,6 +19,7 @@ test helper libraries written for [Bats][bats].
1919Features:
2020- [ error reporting] ( #error-reporting )
2121- [ output formatting] ( #output-formatting )
22+ - [ language tools] ( #language-and-execution )
2223
2324See the [ shared documentation] [ bats-docs ] to learn how to install and
2425load this library.
@@ -121,6 +122,66 @@ actual (3 lines):
121122--
122123```
123124
125+ ## Language and Execution
126+
127+ ### Restricting invocation to specific locations
128+
129+ Sometimes a helper may work properly only when called from a certain
130+ location. Because it depends on variables to be set or some other side
131+ effect.
132+
133+ A good example is cleaning up temporary files only if the test has
134+ succeeded. The outcome of a test is only available in ` teardown ` . Thus,
135+ to avoid programming mistakes, it makes sense to restrict such a
136+ clean-up helper to that function.
137+
138+ ` batslib_is_caller ` checks the call stack and returns ` 0 ` if the caller
139+ was invoked from a given function, and ` 1 ` otherwise. This function
140+ becomes really useful with the ` --indirect ` option, which allows calls
141+ through intermediate functions, e.g. the calling function may be called
142+ from a function that was called from the given function.
143+
144+ Staying with the example above, the following code snippet implements a
145+ helper that is restricted to ` teardown ` or any function called
146+ indirectly from it.
147+
148+ ``` shell
149+ clean_up () {
150+ # Check caller.
151+ if batslib_is_caller --indirect ' teardown' ; then
152+ echo " Must be called from \` teardown'" \
153+ | batslib_decorate ' ERROR: clean_up' \
154+ | fail
155+ return $?
156+ fi
157+
158+ # Body goes here...
159+ }
160+ ```
161+
162+ In some cases a helper may be called from multiple locations. For
163+ example, a logging function that uses the test name, description or
164+ number, information only available in ` setup ` , ` @test ` or ` teardown ` , to
165+ distinguish entries. The following snippet implements this restriction.
166+
167+ ``` shell
168+ log_test () {
169+ # Check caller.
170+ if ! ( batslib_is_caller --indirect ' setup' \
171+ || batslib_is_caller --indirect " $BATS_TEST_NAME " \
172+ || batslib_is_caller --indirect ' teardown' )
173+ then
174+ echo " Must be called from \` setup', \` @test' or \` teardown'" \
175+ | batslib_decorate ' ERROR: log_test' \
176+ | fail
177+ return $?
178+ fi
179+
180+ # Body goes here...
181+ }
182+ ```
183+
184+
124185<!-- REFERENCES -->
125186
126187[ bats ] : https://github.com/sstephenson/bats
0 commit comments