tests/testthat/test_operations.R

library(typeless)

context("Operations")

test_that("dvf function", {

  # decimals are correct
  expect_equal(dvf(1, 3), 0.333)
  expect_equal(dvf(1, 3, 5), 0.33333)
  expect_equal(dvf(1, 1), 1)

  # division by Inf or 0
  expect_equal(dvf(1, Inf), 0)
  expect_equal(dvf(1, 0), Inf)

  # invalid input yields error
  expect_error(dvf(1, "3"))
})

test_that("simp function", {

  # test all 4 methods
  expect_equal(simp(c(0, 0, 3, NA)), c(0, 0, 3, 1))
  expect_equal(simp(c(0, 0, 3, NA), "median"), c(0, 0, 3, 0))
  expect_equal(simp(c(0, 0, 3, NA), "zero"), c(0, 0, 3, 0))
  expect_equal(simp(c(0, 0, 3, NA), "flag"), c(0, 0, 3, "NA"))
})

test_that("mod function", {

  # numerical vector inputs
  expect_equal(mod(c(0, 0, 3)), 0)
  expect_equal(mod(c(1, 2, 3)), 1)

  # character vector input
  expect_equal(mod(c("a", "b", "b")), "b")

  # logical vector input
  expect_equal(mod(c(TRUE, TRUE, FALSE)), TRUE)
})

test_that("pf function", {

  # single value inputs
  expect_equal(pf(1/3), "33.3%")
  expect_equal(pf(1/2), "50%" )
  expect_equal(pf(0/2), "0%" )

  # vector input
  expect_equal(pf(seq(.2, .6, .2)), c("20%", "40%", "60%") )

  # non-finite inputs yield error
  expect_error(pf(1/0))
  expect_error(pf(Inf))
})


test_that("cf function", {

  # single value inputs
  expect_equal(cf(1e+6), "1,000,000")
  expect_equal(cf(1000L), "1,000" )

  # vector input
  expect_equal(cf(c(1e+6, 1e+7)), c("1,000,000", "10,000,000") )

  # non-finite inputs yield error
  expect_error(cf(1/0))
  expect_error(cf(Inf))
})


test_that("convert_unix function", {

  # Date validity
  origin   <-  0L                        # origin is "1970-01-01"
  date_one <- (4 * 24 * 60 * 60 * 1000)  # exactly 4 days offset, "1970-01-05"
  date_two <- (28 * 24 * 60 * 60 * 1000) # exactly 28 days offset, "1970-01-29"

  # test dates conversion
  expect_equal(as.Date(convert_unix(0L)), as.Date("1970-01-01"))
  expect_equal(as.Date(convert_unix(date_one, ms = TRUE)), as.Date("1970-01-05"))
  expect_equal(as.Date(convert_unix(date_two, ms = TRUE)), as.Date("1970-01-29"))

  # hours/minutes/seconds validity
  hour <- (12 * 60 * 60 * 1000) # twelve hours offset
  mins <- (.5 * 60 * 60 * 1000) # half hour offset
  secs <- ( 1 * 1  * 11 * 1000) # 11 seconds offset

  # test hours/minutes/seconds validity
  expect_equal(as.character(convert_unix(hour, ms = TRUE)), "1970-01-01 12:00:00")
  expect_equal(as.character(convert_unix(mins, ms = TRUE)), "1970-01-01 00:30:00")
  expect_equal(as.character(convert_unix(secs, ms = TRUE)), "1970-01-01 00:00:11")

})
ShaulAb/typeless documentation built on May 28, 2019, 3:15 p.m.