I made a factorial function in Racket, which needs to be unit tested for passing passing a very large number that would catch an overflow exception. If the exception is caught, the test should pass, and vice versa. Here is my code.
#lang racket
(provide recursive_factorial)
(provide tail_factorial)
(define (recursive_factorial number)
(cond [(= 0 number) 1]
[(negative? number) (raise-argument-error 'recursive_factorial "negative?" number)]
[(* number (recursive_factorial (- number 1)))]))
(define (tail_factorial number accumulator)
(cond[( = number 0 ) accumulator]
[(negative? number) accumulator (raise-argument-error 'tail_factorial "negative?" number accumulator)]
[(tail_factorial (- number 1) (* accumulator number ))]
))
And here is my attempt to unit test it.
(check-not-exn (λ () (recursive_factorial(100000000)))"stack overflow")
(check-not-exn (λ () (tail_factorial(100000000)))"stack overflow")
With much help I was able to get a negative condition to work. Any help is appreciated.
Your function returns -1
when number
is negative. So shouldn't the test be:
(check-equal? (recursive_factorial -4) -1)
UPDATE
How about:
#lang racket
(provide recursive_factorial)
(define (recursive_factorial number)
(cond [(= 0 number) 1]
[(negative? number) (error 'recursive_factorial
"Cannot pass a negative number")]
[else (* number (recursive_factorial (- number 1)))]))