## Look for detritus files
testme <- as.environment("testme")
local({
  delta <- diff_connections(get_connections(), testme[["testme_connections"]])
  if (any(lengths(delta) > 0)) {
    message(sprintf("Detritus connections generated by test %s:", sQuote(testme[["name"]])))
    print(delta)

    ## Close added connections, because they are expected?
    if (!is.null(delta[["added"]]) &&
        "detritus-connections" %in% testme[["tags"]]) {
      idxs <- delta[["added"]][["index"]]
      for (idx in idxs) {
        tryCatch({
          con <- getConnection(idx)
          close(con)
        }, error = identity)
      }
      delta <- diff_connections(get_connections(), testme[["testme_connections"]])
      if (any(lengths(delta) > 0)) {
        message(sprintf("Detritus connections generated by test %s remains after shutting down expected connections added:", sQuote(testme[["name"]])))
        print(delta)
      } else {
        message(sprintf("No detritus connections remaining from test %s after shutting down expected ones", sQuote(testme[["name"]])))
      }
    }
  }
})


