/
05-unit-tests.qmd
293 lines (205 loc) · 10.5 KB
/
05-unit-tests.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# Unit Tests {#sec-unit-tests}
[Recording](https://youtu.be/nGLur5zwLPY)
Write unit tests for your custom functions using testthat.
```{r, messages = FALSE, filename="Packages required for this chapter"}
library(usethis)
library(testthat)
```
```{r, include = FALSE}
# define apa_t_pair and round0 from last chapter
apa_t_pair <- function(x, y,
dv = "the DV",
level1 = "level 1",
level2 = "level 2") {
t_results <- t.test(x, y, paired = TRUE)
template <- "A paired-samples t-test was conducted to compare {dv} between {level1} (M = {mean1}, SD = {sd1}) and {level2} (M = {mean2}, SD = {sd2}). There was a {non}significant difference; t({df}) = {t_value}, p = {p_value}."
glue::glue(
template,
mean1 = round0(mean(x), 1),
sd1 = round0(sd(x), 1),
mean2 = round0(mean(y), 1),
sd2 = round0(sd(y), 1),
non = ifelse(t_results$p.value < .05, "", "non-"),
df = round0(t_results$parameter, 0),
t_value = round0(t_results$statistic,2),
p_value = round0(t_results$p.value, 3)
)
}
round0 <- function(x, digits = 0) {
fmt <- paste0("%.", digits, "f")
x0 <- sprintf(fmt, x)
return(x0)
}
```
## Set up testhat
Use the following code to set up testing for your package. this makes a directory called `tests` that contains a file called `testthat.R` and a directory called `testthat` where you will keep your testing scripts. It will also add some lines to the `DESCRIPTION` file, so make sure that file doesn't have unsaved changes before you run this.
```{r, eval = FALSE, filename="run in the console"}
usethis::use_testthat()
```
## Set up test
Next, we'll follow the directions from the output text and call `use_test()` to initialise a basic test file and open it for editing.
```{r, eval = FALSE, filename="run in the console"}
usethis::use_test("apa_t_pair")
```
A new file (`tests/testthat/apa_t_pair.R`) will open with the following text. It you run it, you should get a message saying it passed.
```{r, filename="tests/testthat/apa_t_pair.R"}
test_that("multiplication works", {
expect_equal(2 * 2, 4)
})
```
Change the default label for this test. You can label these whatever you want (it *really* doesn't matter); I usually start with "defaults" and test the most basic example to make sure the function defaults work as expected. Delete the demo code between the curly brackets.
```{r, eval = FALSE, filename="tests/testthat/apa_t_pair.R"}
test_that("defaults", {
})
```
Set `x` and `y` as two small static `r glossary("vector", "vectors")` (don't use `rnorm()` or anything that makes random numbers). Then assign the value of `apa_t_pair(x, y)` to `result` and the expected result to `expected`. Finally, use the function `expect_equal()` to compare the obtained and expected result.
```{r, filename="tests/testthat/apa_t_pair.R"}
test_that("defaults", {
x <- c(1,2,3,4,5)
y <- c(2,3,2,5,6)
result <- apa_t_pair(x, y)
expected <- "A paired-samples t-test was conducted to compare the DV between level 1 (M = 3.0, SD = 1.6) and level 2 (M = 3.6, SD = 1.8). There was a non-significant difference; t(4) = -1.50, p = 0.208."
expect_equal(result, expected)
})
```
That particular example was `r glossary("non-significant", "significance")`. Let's add a version that does show a significant difference and make sure the text changes appropriately.
```{r, filename="tests/testthat/apa_t_pair.R"}
test_that("defaults-sig", {
x <- c(1,2,1,3,1)
y <- c(5,3,2,5,6)
result <- apa_t_pair(x, y)
expected <- "A paired-samples t-test was conducted to compare the DV between level 1 (M = 1.6, SD = 0.9) and level 2 (M = 4.2, SD = 1.6). There was a significant difference; t(4) = -3.20, p = 0.033."
expect_equal(result, expected)
})
```
No let's change the `r glossary("default values")` for the DV and labels.
```{r, filename="tests/testthat/apa_t_pair.R"}
test_that("non-defaults", {
x <- c(1,2,1,3,1)
y <- c(5,3,2,5,6)
result <- apa_t_pair(x, y, dv = "the score", "Group A", "Group B")
expected <- "A paired-samples t-test was conducted to compare the score between Group A (M = 1.6, SD = 0.9) and Group B (M = 4.2, SD = 1.6). There was a significant difference; t(4) = -3.20, p = 0.033."
expect_equal(result, expected)
})
```
## Test-driven development
You can use tests to help you develop your package. First, think of something you want to add or change. Then write a test that checks if your function is doing that new thing. It will, of course, fail, but then your task is to alter the function code until the test passes.
For example, it would be nice to give a custom error message if x and y are identical, since this is almost always a mistake and you can't calculate any test statistics.
```{r}
x <- c(1,2,1,4,1)
apa_t_pair(x, x)
```
::: {.callout-warning}
You may get an error above instead of "There was a NAsignificant difference; t(4) = NaN, p = NaN.", this means that you've changed a default setting, but I'm having trouble figuring out what (one of my computers returns an error and two return the text above). I'll update this when I figure it out. Regardless, we want to replace that opaque error with an intelligible error.
:::
The first step is to write a test that fails. Wrap the code `apa_t_pair(x, x)` inside the function `expect_error()`, which will pass if the code produces the specified error message and fail if it doesn't.
```{r, error = TRUE, filename="tests/testthat/apa_t_pair.R"}
test_that("same x and y", {
x <- c(1,2,1,4,1)
expect_error( apa_t_pair(x, x),
regexp = "x and y cannot be identical",
fixed = TRUE )
})
```
::: {.callout-note}
The function `expect_error()` can use regular expressions to test for patterns. For example, `"is not allowed$"` will match any string that ends with "is not allowed". Regex is powerful, but can be tricky to use. If you want to test if the returned error text is **exactly** the same as the `regexp` string, set `fixed = TRUE`.
:::
Now we can edit the function `apa_t_pair()` until the test passes. Add a few lines of code at the start of the function to check if all of the values in `x` are the same as all of the values in `y`, and display an error message if they are.
```{r, filename="R/apa_t_pair.R"}
apa_t_pair <- function(x, y,
dv = "the DV",
level1 = "level 1",
level2 = "level 2") {
# warn about identical values
if (all(x == y)) {
stop("x and y cannot be identical")
}
t_results <- t.test(x, y, paired = TRUE)
template <- "A paired-samples t-test was conducted to compare {dv} between {level1} (M = {mean1}, SD = {sd1}) and {level2} (M = {mean2}, SD = {sd2}). There was a {non}significant difference; t({df}) = {t_value}, p = {p_value}."
glue::glue(
template,
mean1 = round0(mean(x), 1),
sd1 = round0(sd(x), 1),
mean2 = round0(mean(y), 1),
sd2 = round0(sd(y), 1),
non = ifelse(t_results$p.value < .05, "", "non-"),
df = round0(t_results$parameter, 0),
t_value = round0(t_results$statistic,2),
p_value = round0(t_results$p.value, 3)
)
}
```
Now the test should pass.
```{r, error = TRUE, filename="tests/testthat/apa_t_pair.R"}
test_that("same x and y", {
x <- c(1,2,1,4,1)
expect_error( apa_t_pair(x, x),
regexp = "x and y cannot be identical",
fixed = TRUE )
})
```
Now that we have 4 tests for this function, we can run them all by clicking on **`Run Tests`** in the upper right corner of the `r glossary("panes", "source pane")`. If all goes well, you'll see the following in the Build tab:
::: {.cell-output}
```
==> Testing R file using 'testthat'
ℹ Loading demopkg
══ Testing test-apa_t_pair.R ═════
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 4 ] Done!
Test complete
```
:::
## Testing data
You can also set up tests for a data object.
```{r, eval = FALSE, filename="run in the console"}
usethis::use_test("self_res_att")
```
Let's check that the `data()` function can load this data set and that it has the expected dimensions. We can also check if the column `sex` is a factor.
```{r, eval = FALSE, filename="tests/testthat/self_res_att.R"}
test_that("data available", {
data("self_res_att")
expect_true( exists("self_res_att") )
expect_equal(ncol(self_res_att), 16)
expect_equal(nrow(self_res_att), 108)
expect_true(is.factor(self_res_att$sex))
})
```
## Multiple tests {#sec-multiple-tests}
You can run all of the tests for all of the functions in your package by clicking on **`Test`** in the Build Tab or typing `devtools::test()` in the console. Here, you'll get one row for each test file (usually one test file per function) and a summary of how many tests Failed (F), gave unexpected warnings (W), were skipped (S), or passed (OK).
::: {.cell-output}
```
==> devtools::test()
ℹ Testing demopkg
✔ | F W S OK | Context
✔ | 4 | apa_t_pair
✔ | 3 | self_res_att
══ Results ═══════════════════════
Duration: 0.1 s
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 7 ]
```
:::
Sometimes you want to set tests to skip because they take too long or cause problems when you submit a package to CRAN. Testthat has a number of functions that start with `skip` that allow you to skip any following tests under different circumstances.
You can also set up tests for a data object.
```{r, eval = FALSE, filename="run in the console"}
usethis::use_test("self_res_att")
```
Let's check that the `data()` function can load this data set and that it has the expected dimensions.
```{r, eval = FALSE, filename="tests/testthat/self_res_att.R"}
test_that("data available", {
data("self_res_att")
expect_true( exists("self_res_att") )
expect_equal(ncol(self_res_att), 16)
expect_equal(nrow(self_res_att), 108)
})
```
## Glossary
```{r, echo = FALSE, results='asis'}
glossary_table()
```
## Further Resources
* [Testing Basics](https://r-pkgs.org/testing-basics.html) from @r-packages
* [testthat](https://testthat.r-lib.org/)
## Further Practice
1. Set up tests for `round0`. Make sure that this function gives the expected result for different values of `digits` and rounds values appropriately. Remember that the results you're trying to match is a character data type, not a numeric value.
1. Use test-driven development to add a custom error message to `apa_t_pair()` if the length of `x` and `y` are not the same.
1. Add further sense checks that the column types are as expected for `self_res_att`.
1. Add unit tests for any other functions you've created.