tests/testthat/test_file_functions.R

library(cermbTools)

context("Files and paths")

test_that("fileName works with simple names", {
  expect_equal(fileName("foo.txt"), "foo.txt")
  expect_equal(fileName("./foo.txt"), "foo.txt")
})

test_that("fileName works with full paths", {
  expect_equal(fileName("c:/michael/data/somewhere/firehistory/pretend.dat"), "pretend.dat")
})

test_that("fileName ignores leading and trailing whitespace", {
  expect_equal(fileName("  c:/michael/foo.txt  "), "foo.txt")
})

test_that("fileExtension works correctly", {
  inputs <- c("foo.txt",
              "bar.dat",
              "baz",
              "./some/where/foo.csv",
              "c:/michael/data/bar.dat",
              "s:\\data\\blah\\blah\\baz.txt",
              "s:/data/baz")

  expected <- c("txt", "dat", "", "csv", "dat", "txt", "")

  expect_equal(fileExtension(inputs), expected)
})

test_that("fileExtension returns an empty string when there is no extension", {
  expect_equal(fileExtension("foo"), "")
})

test_that("fileExtension ignores leading and trailing whitespace", {
  expect_equal(fileExtension("  c:/michael/foo.txt  "), "txt")
})

test_that("fileHasExtension correctly detects extensions", {
  inputs <- c("foo", "foo.txt", "foo.", "c:/michael/foo.txt", "./foo")
  expected <- c(FALSE, TRUE, FALSE, TRUE, FALSE)

  expect_equal(fileHasExtension(inputs), expected)
})

test_that("fileHasExtension ignores leading and trailing whitespace", {
  inputs <- c("  foo  ", "  foo.txt  ")
  expected <- c(FALSE, TRUE)

  expect_equal(fileHasExtension(inputs), expected)
})

test_that("fileRemoveExtension works correctly", {
  inputs <- c("foo", "foo.txt", "foo.", "c:/michael/foo.txt", "./foo")
  expected <- c("foo", "foo", "foo", "c:/michael/foo", "./foo")

  expect_equal(fileRemoveExtension(inputs), expected)
})

test_that("fileRemoveExtension leaves trailing dot when specified", {
  inputs <- c("c:/michael/foo.", "c:/michael/foo.dat")
  expected <- c("c:/michael/foo.", "c:/michael/foo")

  expect_equal(fileRemoveExtension(inputs, removeTrailingDot = FALSE), expected)
})

test_that("fileRemoveExtension ignores leading and trailing whitespace", {
  inputs <- c(" foo.txt ", " foo ")
  expected <- c("foo", "foo")

  expect_equal(fileRemoveExtension(inputs), expected)
})

test_that("fileSplitPaths works correctly", {
  inputs <- c("foo", "foo.txt", "./foo.txt", "c:/michael/data/foo.txt")

  expected <- matrix( c(
    "", "foo",
    "", "foo.txt",
    ".", "foo.txt",
    "c:/michael/data", "foo.txt"
    ),
    ncol = 2, byrow = TRUE)
  colnames(expected) <- c("path", "file")

  res <- fileSplitPath(inputs)
  expect_is(res, "matrix")
  expect_equal(res, expected)
})
mbedward/cermbTools documentation built on May 22, 2019, 12:19 p.m.