Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bb048d7

Browse files
committed
Add test driver
1 parent 93cc08e commit bb048d7

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

test_cachematrix.R

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
library(testthat)
2+
# I don't know how to make proper packages yet, so I'll hack with `source` for
3+
# now.
4+
#library(cachematrix)
5+
source("cachematrix.R")
6+
7+
# Pre-computed results
8+
setup_fixtures <- function() {
9+
xvect <- c(2,3,0,3,0,2,2,1,1)
10+
xm <- matrix(xvect,3,3)
11+
xvect_inv <- c(2,3,-6,-1,-2,4,-3,-4,9)
12+
xm_inv <- matrix(xvect_inv,3,3)
13+
14+
xvect2 <- xvect
15+
xvect2[1] <- 1
16+
xm2 <- matrix(xvect2,3,3)
17+
xvect2_inv <- c(-2,-3,6,1,1,-2,3,5,-9)
18+
xm2_inv <- matrix(xvect2_inv,3,3)
19+
20+
list(xm=xm, xm_inv=xm_inv, xm2=xm2, xm2_inv=xm2_inv)
21+
}
22+
23+
test_that("makeCacheMatrix makes a matrix-ish", {
24+
fix <- setup_fixtures()
25+
26+
cm <- makeCacheMatrix(fix$xm)
27+
28+
expect_that(cm$get(), equals(fix$xm))
29+
})
30+
31+
test_that("cacheSolve produces inverted matrix", {
32+
fix <- setup_fixtures()
33+
34+
cm <- makeCacheMatrix(fix$xm)
35+
cm_inv <- cacheSolve(cm)
36+
37+
expect_that(cm_inv, equals(fix$xm_inv))
38+
39+
})
40+
41+
test_that("cacheSolve uses cache", {
42+
fix <- setup_fixtures()
43+
44+
cm <- makeCacheMatrix(fix$xm)
45+
cm_inv <- cacheSolve(cm)
46+
47+
expect_that(cacheSolve(cm), shows_message("getting cached data"))
48+
})
49+
50+
test_that("set invalidates cache", {
51+
fix <- setup_fixtures()
52+
53+
cm <- makeCacheMatrix(fix$xm)
54+
cm_inv <- cacheSolve(cm)
55+
56+
expect_that(cm$set(fix$xm2), shows_message("invalidating cache"))
57+
cm_inv2 <- cacheSolve(cm)
58+
59+
expect_that(cm_inv2, not(equals(cm_inv)))
60+
expect_that(cm_inv2, equals(fix$xm2_inv))
61+
})

0 commit comments

Comments
 (0)