|
| 1 | +find_expectation_srcref <- function(test_code_frame = NULL, top = caller_env()) { |
| 2 | + # It's not possible to give useful srcrefs interactively so don't even try |
| 3 | + path <- getOption("testthat_path") |
| 4 | + if (is.null(path)) { |
| 5 | + return(NULL) |
| 6 | + } |
| 7 | + |
| 8 | + # Scope our search to the current file loaded with source_file() |
| 9 | + file_srcref <- srcref(srcfile(path), c(1, 1, 1e5, 1e5)) |
| 10 | + |
| 11 | + # Now attempt to narrow the scope to a call that leads to test_code(). That's |
| 12 | + # usually test_that() but might be describe(), it(), or another wrapper. |
| 13 | + testthat_srcref <- find_srcref( |
| 14 | + top = test_code_frame, |
| 15 | + container = file_srcref |
| 16 | + ) |
| 17 | + |
| 18 | + # Now we can find the bottom-most call with a srcref that's inside that scope |
| 19 | + call_srcref <- find_srcref( |
| 20 | + top = top, |
| 21 | + bottom = test_code_frame, |
| 22 | + container = testthat_srcref %||% file_srcref |
| 23 | + ) |
| 24 | + |
| 25 | + # If we can't find that we fall back to the test |
| 26 | + call_srcref %||% testthat_srcref |
| 27 | +} |
| 28 | + |
| 29 | +find_srcref <- function(bottom = NULL, |
| 30 | + top = caller_env(), |
| 31 | + container = NULL) { |
| 32 | + |
| 33 | + idx <- sys_index(bottom, top) |
| 34 | + calls <- sys.calls()[rev(idx)] |
| 35 | + |
| 36 | + for (call in calls) { |
| 37 | + srcref <- attr(call, "srcref") |
| 38 | + |
| 39 | + if (!is.null(srcref)) { |
| 40 | + if (is.null(container) || srcref_inside(srcref, container)) { |
| 41 | + return(srcref) |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + NULL |
| 47 | +} |
| 48 | + |
| 49 | +srcref_inside <- function(needle, haystack) { |
| 50 | + stopifnot(inherits(needle, "srcref"), inherits(haystack, "srcref")) |
| 51 | + |
| 52 | + needle_file <- attr(needle, "srcfile")$filename |
| 53 | + haystack_file <- attr(haystack, "srcfile")$filename |
| 54 | + |
| 55 | + if (!identical(needle_file, haystack_file)) { |
| 56 | + return(FALSE) |
| 57 | + } |
| 58 | + |
| 59 | + sign_pair <- function(x, y) { |
| 60 | + diff <- y - x |
| 61 | + if (diff[1] == 0) sign(diff[2]) else sign(diff[1]) |
| 62 | + } |
| 63 | + |
| 64 | + sign_pair(needle[1:2], haystack[1:2]) <= 0 && |
| 65 | + sign_pair(needle[3:4], haystack[3:4]) >= 0 |
| 66 | +} |
| 67 | + |
| 68 | +sys_index <- function(bottom = NULL, top = caller_env()) { |
| 69 | + frames <- sys.frames() |
| 70 | + if (is.null(bottom)) { |
| 71 | + bottom_idx <- 1 |
| 72 | + } else { |
| 73 | + bottom_idx <- Position(function(env) identical(bottom, env), frames) |
| 74 | + if (is.na(bottom_idx)) { |
| 75 | + abort("Can't find `bottom` on stack") |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + top_idx <- Position(function(env) identical(top, env), frames) |
| 80 | + if (is.na(top_idx)) { |
| 81 | + abort("Can't find `top` on stack") |
| 82 | + } |
| 83 | + |
| 84 | + seq2(bottom_idx, top_idx) |
| 85 | +} |
0 commit comments