tests/testthat/test-build.R

describe("build_function", {
  it("should return a function", {
    plan <- plan()
    built <- build_function(plan)
    expected <- function() {}
    expect_equal(built, expected)
  })

  it("should add inputs as function args", {
    plan <- plan(x)
    built <- build_function(plan)
    expected <- function(x) {
      force(x)
    }
    expect_equal(built, expected)

    plan <- plan(x, y)
    built <- build_function(plan)
    expected <- function(x, y) {
      force(x)
      force(y)
    }
    expect_equal(built, expected)

    plan <- plan(x, y = 10)
    built <- build_function(plan)
    expected <- function(x, y = 10) {
      force(x)
      force(y)
    }
    expect_equal(built, expected)

    plan <- plan(x, y = x + 1)
    built <- build_function(plan)
    expected <- function(x, y = x + 1) {
      force(x)
      force(y)
    }
    expect_equal(built, expected)
  })

  it("should add steps as function body", {
    plan <- plan() %>%
      add_steps(x = function() {})
    built <- build_function(plan)
    expected <- function() {
      x <- .execute_step("x")
      .return_step("x")
    }
    expect_equal(built, expected)

    # multiple
    plan <- plan() %>%
      add_steps(
        x = function() {},
        y = function() {},
      )
    built <- build_function(plan)
    expected <- function() {
      x <- .execute_step("x")
      y <- .execute_step("y")
      .return_step("y")
    }
    expect_equal(built, expected)

    # with args
    plan <- plan() %>%
      add_steps(
        x = function() {},
        y = function(x) {},
      )
    built <- build_function(plan)
    expected <- function() {
      x <- .execute_step("x")
      y <- .execute_step("y", x = x)
      .return_step("y")
    }
    expect_equal(built, expected)
  })
})

describe("execute", {
  it("should return invisibly if the returned values was invisible", {
    plan <- plan() %>%
      add_steps(
        x = function() {
          invisible(1000)
        }
      )
    expect_invisible(plan %>% execute())


    plan <- plan() %>%
      add_steps(
        x = function() invisible(1000),
        y = function() {}
      )
    expect_invisible(plan %>% execute(.return = "x"))
  })

  it("should return all results for `.return` specified as `..all..`", {
    result <- plan() %>%
      add_steps(x = function() {}) %>%
      execute(.return = ..all..)
    expect_equal(result, list(x = NULL))

    result <- plan() %>%
      add_steps(
        x = function() 1,
        y = function() 2,
      ) %>%
      execute(.return = ..all..)
    expect_equal(result, list(x = 1, y = 2))

    result <- plan() %>%
      add_steps(
        x = function() 1,
        y = function() 2,
        z = function(x, y) x + y
      ) %>%
      execute(.return = ..all..)
    expect_equal(result, list(x = 1, y = 2, z = 3))
  })
})
shunsambongi/planner documentation built on Aug. 19, 2022, 9:57 a.m.