isas-tests.Rin 2.41 KB
Newer Older
1
#### Produce an R test script -*- R -*-
2 3 4 5 6 7 8 9 10 11 12 13
## The logic here (BDR, 2003-02-02) is
## identify all is. and as. functions which might be thought of
## as precursors to is() and as().  Identify only generics.
##
## Then for a set of boundary-case inputs x, if as.foo(x) works
## check that is.foo(as.foo(x)) is true.
## Also check idempotency: as.foo(as.foo(x)) == as.foo(x)
## and that as.foo(x) == x iff is.foo(x) is true.
##
## One problem with the last is that no realistic x's are used.
##
ls.base <- c(ls("package:base"), ls("package:stats"))
14 15 16
base.is.f <- sapply(ls.base, function(x) is.function(get(x)))
bi <- ls.base[base.is.f]
iroot <- substring(is.bi <- bi[substring(bi,1,3) == "is."],4)
17 18
## is.single is a dummy
iroot <- iroot[-match("single", iroot)]
19
aroot <- substring(as.bi <- bi[substring(bi,1,3) == "as."],4)
20 21 22
## eliminate as.foo methods: there are no is.foo methods
## this works because data.frame.*  has no other matches for data.
aroot <- aroot[!duplicated(sub("\\..*", "", aroot))]
23
root <- intersect(iroot, aroot) # both an  is.foo and as.foo function exist
24 25 26 27 28 29 30

ex.list <- expression(integer(0), NULL, list(), 1:1, pi, "1.3", list(a=1),
    as.data.frame(character(0)))

##--- producing the real R script:
sink("isas-tests.R")

31 32
cat(".proctime00 <- proc.time()\n",
    "isall.equal <- function(x,y)",
33
    "typeof(x) == typeof(y) && is.logical(r <- all.equal(x,y, tol=0)) && r \n",
34
    sep="\n")
35

36 37
cat("report <- function(x) {print(x); stopifnot(x)}\n")

38 39 40 41 42
cat("options(error = expression(NULL))",
    "# don't stop on error in batch\n##~~~~~~~~~~~~~~\n")
for(x in ex.list) {
    cat("\n###--------\n x <- ", deparse(x), "\n", sep="")
    ## is.foo(as.foo( bar )) #>> TRUE :
43 44 45 46
    for(r in root) {
        cat("res <- try(as.", r, "( x ), silent = TRUE)\n", sep="")
        cat("if(!inherits(res, 'try-error')) report(is.",r,"(res))\n", sep="")
    }
47 48
    cat("\n")
    ## if(is.foo(bar))  bar ``=='' as.foo(bar) :
49 50 51
    for(r in root) {
        cat("res <- try(as.", r, "( x ), silent = TRUE)\n", sep="")
        cat("if(!inherits(res, 'try-error'))\n   report({if(is.",r,"(x)) { ",
52
            "cat('IS: ');all.equal(x, res, tol=0)\n",
53 54
            "   } else   !isall.equal(x, res)})\n", sep="")
    }
55 56 57

    ## f <- as.foo(x)  ==>  as.foo(f) == f :
    for(r in aroot)
58
        cat("f <- try(as.",r,"( x ), silent = TRUE)\n  if(!inherits(f, 'try-error')) report(identical(f, as.",r,"( f )))\n", sep="")
59
}
60
cat("cat('Time elapsed: ', proc.time() - .proctime00,'\\n')\n")