Test a function: Difference between revisions
m
syntax highlighting fixup automation
(Add Tailspin solution) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 13:
Using [http://www.ccs.neu.edu/home/cce/acl2/doublecheck.html DoubleCheck]:
<
(if (zp i)
(mv xs ys)
Line 48:
(defproperty palindrome-test
(p :value (random-palindrome))
(is-palindrome p))</
=={{header|Ada}}==
Line 55:
For larger testing frameworks, there are packages like [https://github.com/AdaCore/aunit Aunit] or [https://github.com/pyjarrett/trendy_test Trendy Test]
<
procedure Test_Function is
Line 82:
Ada.Text_IO.Put_Line("Test Passed!");
end;
end Test_Function;</
Ada 2012 introduced a new way to specify functions and test their correctness: Pre- and Postoconditions.
<
with Post => Palindrome'Result =
(Text'Length < 2 or else
((Text(Text'First) = Text(Text'Last)) and then
Palindrome(Text(Text'First+1 .. Text'Last-1))));</
=={{header|Arturo}}==
<
s = reverse s
]
Line 103:
]
loop tests => ensure</
{{out}}
Line 112:
there is no "well known" testing library, but here is a simple testing framework: <br>
test library: assert.ahk
<
;; assert(a, b, test=2)
assert(a, b="blank", test=0)
Line 149:
return 1
}</
test example:
<
, "palindrome test")
assert(broken("in girum imus nocte et consumimur igni"), "works"
Line 171:
#Include assert.ahk
#Include palindrome.ahk</
=={{header|Brat}}==
<
palindrome? = { str |
Line 197:
assert { palindrome? "blah blah" }
}
}</
Output:
Line 212:
=={{header|C}}==
<
int IsPalindrome(char *Str);
Line 220:
assert(IsPalindrome("alice"));
}
</syntaxhighlight>
=={{header|C sharp}}==
Line 226:
First, using the VisualStudio TestTools for unit tests. I'm testing both of the methods for palindrome detection created in the article.
<syntaxhighlight lang="csharp">
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalindromeDetector.ConsoleApp;
Line 260:
}
}
}</
Second, NUnit tests. Couldn't test these because of namespace issues with NUnit, but I'm sure they work.
<syntaxhighlight lang="csharp">
using NUnit.Framework;
using PalindromeDetector.ConsoleApp;
Line 298:
}
}
}</
=={{header|C++}}==
<
#include <string>
Line 308:
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
</syntaxhighlight>
Line 314:
test can be tested at compile time - failing the test will cause a compilation failure.
<
{
static_assert(is_palindrome("ada"));
Line 325:
int main()
{
}</
{{out}}
<pre>
Line 343:
A popular testing framework is gtest.
<
TEST(PalindromeSuite, Test1)
Line 352:
EXPECT_FALSE(is_palindrome("ada")); // will fail
EXPECT_TRUE(is_palindrome("C++")); // will fail
}</
{{out}}
<pre>
Line 383:
Boost also has a testing framework.
<
#include <boost/test/unit_test.hpp>
Line 393:
BOOST_CHECK( is_palindrome("ada") == false); // will fail
BOOST_CHECK( is_palindrome("C++") == true); // will fail
}</
{{out}}
<pre>
Line 404:
=={{header|Clojure}}==
<
(use 'clojure.test)
Line 412:
(run-tests)
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(defpackage :rosetta
(:use :cl
Line 516:
NIL
|#
</syntaxhighlight>
=={{header|Crystal}}==
<
describe "palindrome" do
Line 534:
def palindrome(s)
s == s.reverse
end</
<pre>
Line 542:
=={{header|D}}==
<
assert(isPalindrome("racecar"));
assert(isPalindrome("bob"));
assert(!isPalindrome("alice"));
}</
=={{header|Delphi}}==
Line 552:
Using built in assertions.
<
Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Assert(not IsPalindrome('123'), '123 is not a valid palindrome');</
Using [[wp:DUnit|DUnit]], an open source unit testing framework that is bundled with Delphi.
<
Check(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Check(not IsPalindrome('123'), '123 is not a valid palindrome');</
=={{header|E}}==
Line 568:
The standard testing tool in E is Updoc, a system which takes test scripts formatted in the same style as a [[REPL]] session and verifies that executing them produces the specified result values.
<
? def isPalindrome(string :String) {
Line 617:
? (x + xreversed).size()
# value: 131072</
=={{header|EchoLisp}}==
EchoLisp provides (assert <true-value?> ["fail-message"]) and (check-expect <expression> <expected-result>).
<
(assert (palindrome? "aba")) → #t
(assert (palindrome? "abbbca") "palindrome fail")
Line 631:
😐 warning: #t : check failed : (palindrome? abcda) → #f
(assert (palindrome? "un roc lamina l animal cornu")) → #t
</syntaxhighlight>
=={{header|Erlang}}==
This is a unit test so I use Eunit. For system tests "Common Test" would be used. Both are built in.
<syntaxhighlight lang="erlang">
-module( palindrome_tests ).
-compile( export_all ).
Line 643:
abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
</syntaxhighlight>
{{out}}
<pre>
Line 652:
=={{header|Euphoria}}==
<
--unittest in standard library 4.0+
include std/unittest.e
Line 664:
test_report()
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
{{libheader|NUnit}}
<
let a = s.ToUpper().ToCharArray()
Array.rev a = a
Line 683:
[<Test>]
member x.Test02() =
Assert.IsFalse(palindrome "hello")</
=={{header|Factor}}==
Line 690:
''palindrome/palindrome.factor''
<
IN: palindrome
: palindrome? ( string -- ? ) dup reverse = ;</
''palindrome/palindrome-tests.factor''
<
IN: palindrome.tests
[ t ] [ "racecar" palindrome? ] unit-test
[ f ] [ "ferrari" palindrome? ] unit-test</
To run these tests from the listener:
<
Factor's tutorial, [http://docs.factorcode.org/content/article-first-program.html Your first program], uses ''palindrome?'' as its example. The tutorial shows how to create tests for ''palindrome?'' and how to fix a failing test.
Line 713:
To use the built-in test library, the program must be compiled into a pod. The layout for a simple pod and its build file is given in the [http://fantom.org/doc/docIntro/HelloWorld.html#pod documentation], and also information for adding and running the [http://fantom.org/doc/docTools/Fant.html test files].
<
class TestPalindrome : Test
{
Line 727:
}
}
</syntaxhighlight>
=={{header|Fortran}}==
Line 735:
=={{header|FreeBASIC}}==
{{trans|VBA}}
<
Sub StrReverse(Byref text As String)
Dim As Integer x, lt = Len(text)
Line 778:
Next i
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 798:
=={{header|Go}}==
Using Go's standard command, go test.
<
import "testing"
Line 828:
}
}
}</
Output of go test:
<pre>
Line 839:
A notable testing library for Haskell is QuickCheck. It works in a way particularly supported by Haskell's type inference: you provide a function return a boolean, the test, and QuickCheck automatically generates random values for the function's parameters and checks that it returns <code>True</code> for all of them.
<
isPalindrome :: String -> Bool
Line 858:
putStr "Odd palindromes: " >> quickCheck (\s -> not (null s) ==> isPalindrome (s ++ (tail.reverse) s))
putStr "Non-palindromes: " >> quickCheck (\i s -> not (null s) && 0 <= i && i < length s && i*2 /= length s
==> not (isPalindrome (take i s ++ "•" ++ drop i s)))</
The <code>==></code> operator is used to constrain the randomly-generated values: the second test needs a nonempty string, and the third needs an index into the string that is not the exact middle.
Line 868:
for failure. There is no standard framework, but the following example shows
how these tests might be handled.
<
s := "ablewasiereisawelba"
assert{"test1",palindrome(s)}
Line 887:
procedure assertFailure(A)
if @A[2] then write(@A[1],": failed")
end</
Which outputs:
Line 901:
Tests are contained in a test script <tt>c:\mypath\palindrome_test.ijs</tt> with the following contents:
<
NB. Basic testing
Line 916:
test_palinB=: monad define
assert isPalin0 'ab'
)</
Example Usage:
<
unittest 'c:\mypath\palindrome_test.ijs'
Test: c:\mypath\palindrome_test.ijs
palinA .................................. OK
palinB .................................. OK</
=={{header|Java}}==
{{works with|Java|5}}<br>
{{libheader|JUnit}}
<
import static ExampleClass.rPali; // or from wherever it is defined
import org.junit.*;
Line 975:
//some code that should throw a WhateverException
}
}</
Most [[IDE]]s that support Java will have JUnit built in or will have an easy-to-use plugin for it. For those that don't use these IDEs, test classes can be run from a normal main method and their results will print to standard output:
<
public static main(String[] args){
org.junit.runner.JUnitCore.runClasses(PalindromeTest.class/*, other classes here if you have more*/);
}
}</
=={{header|JavaScript}}==
Line 990:
{{works with|Browserify}}
<
describe('palindrome', () => {
Line 1,013:
});
})
});</
Output:
Line 1,053:
Here is an example of a file with four test case triplets:
<
.
1
Line 1,071:
def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial
3
6</
If the file is named, say, test.txt, then the tests can be run by executing: jq --run-tests < test.txt
jq 1.4 produces very verbose output because an execution trace is included. In this article, only the key output lines are shown. The output that results from running the four test cases above is, in abbreviated form, as follows:
<
Testing '.' at line number 3
Line 1,084:
Testing 'def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial' at line number 18
3 of 4 tests passed (0 malformed)
</syntaxhighlight>
===Testing jq Libraries===
Line 1,092:
For example, suppose the file library.jq contains the following definitions:
<
def palindrome: explode as $in | ($in|reverse) == $in;</
and that the file test-library.txt contains the two test triplets:
<
3
6
Line 1,104:
import "library" as lib; lib::palindrome
"salàlas"
true</
Then the tests can be run by invoking jq in the usual way:
<
=={{header|Jsish}}==
Line 1,115:
Given the [[Palindrome detection]] solution of
<
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,121:
}
return str === str.split('').reverse().join('');
}</
''jsish'' allows adding ''echo mode'' lines, (which are lines with a semi-colon ; in column 1 followed by an expression, with a closing semi-colon)
Line 1,138:
Ok, looks good so far. ''jsish'' also has a run unit tests mode, <code>-u</code>. Along with running basic "did the program crash", -u also handles special comment sections for expectations.
<
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,154:
isPalindrome('CUB') ==> false
=!EXPECTEND!=
*/</
Giving
Line 1,179:
CUB is not an exact palindrome. Putting that back to pass again, and adding a few other tests, in particular for exercising the ''exact palindrome'' flag that ignores case and punctuation when set to false. (A false palindrome so to speak).
<
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,201:
isPalindrome('CUB') ==> false
=!EXPECTEND!=
*/</
That's all good, but after looking at --U output, it'll mean an extra edit to the file to add the expectations. ''jsish'' to the rescue, and automatically updating the expectation block:
Line 1,210:
Which now looks like
<
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,238:
isPalindrome('A man, a plan, a canal; Panama!', true) ==> false
=!EXPECTEND!=
*/</
Easy peasy. ''Maybe too easy'', auto update of unit tests should not be run until you know you have valid tests and known results. If there is a bug in the expression, <code>-u -update true</code> will gladly update a script with invalid results. The <code>-update true</code> feature should be treated as a helper, not a "turn off brain now" crutch. Very handy on initial create, or when messaging changes in code under test, but to be treated with respect and care.
Line 1,244:
Echo lines are not the only thing captured by <code>jsish -u</code> mode. All outputs are captured and can be compared in the EXPECT block. It even allows for sample input testing.
<
var trial = console.input();
puts(trial.replace(/a/g, 'b'));
Line 1,258:
bbccbb
=!EXPECTEND!=
*/</
{{out}}
Line 1,280:
{{works with|Julia|0.6}}
<
include("Palindrome_detection.jl")
Line 1,299:
@test !palindrome("a11")
@test !palindrome("012")
end</
{{out}}
Line 1,309:
=={{header|Kotlin}}==
Kotlin can use various JVM testing frameworks including its own kotlin-test module. However, for simple cases, it is easier to use the 'assert' function built into its standard library which will throw an AssertionError if the condition is false and assertions are enabled using java's -ea option when the application is run:
<
fun isPalindrome(s: String) = (s == s.reversed())
Line 1,323:
}
}
}</
{{out}}
Line 1,334:
The following example uses the [https://bitbucket.org/bfad/lspec/ LSpec Library]:
<
define isPalindrome(text::string) => {
Line 1,370:
// Run the tests and get the summary
// (This normally isn't in the code as the test suite is run via command-line.)
lspec->stop</
{{out}}
Line 1,379:
=={{header|Lua}}==
<
assert( ispalindrome("ABCDE") )</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
On[Assert];myFun[1.0]</
{{out}}
<pre>Assert::asrtf: Assertion y>5 failed.
Line 1,391:
=={{header|NetRexx}}==
{{libheader|JUnit}}
<
options replace format comments java crossref savelog symbols binary
Line 1,434:
return
</syntaxhighlight>
;Output
<pre>
Line 1,446:
=={{header|Nim}}==
Using assertions (no output means all tests were correct; this only works with debug builds!):
<
result = newString(s.len)
for i, c in s:
Line 1,463:
assert(not isPalindrome("ba_ ab"))
assert(isPalindrome("ba _ ab"))
assert(not isPalindrome("abab"))</
Using the “unittest” module:
<
proc reversed(s: string): string =
Line 1,491:
test "no palindrome":
check isPalindrome("foo") == false</
{{out}}:
Line 1,511:
ocaml unix.cma -I +oUnit oUnit.cma palindrome.cmo palindrome_tests.ml
<
open Palindrome
Line 1,536:
"test_palindrome_5" >:: test_palindrome_5]
let _ =
run_test_tt_main suite</
=={{header|Oforth}}==
Unit tests are a built-in functionality. If Oforth is run using --t option, all tests are checked. Otherwise, tests are not checked :
<
test: ["abba" isPalindrome ]
test: [ "abcba" isPalindrome ]</
=={{header|PARI/GP}}==
Line 1,561:
{{trans|Raku}}
<
use strict;
use warnings;
Line 1,597:
ok palindrome_r == $expect, 1, "palindrome_r: $note";
ok palindrome_e == $expect, 1, "palindrome_e: $note";
}</
The program produces TAP output.
Line 1,652:
{{libheader|Phix/basics}}
The only golden rule here is to invoke test_summary() after any [block of] tests have been run, everything else is optional.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"0.8.2"</span><span style="color: #0000FF;">)</span>
Line 1,682:
<span style="color: #7060A8;">test_summary</span><span style="color: #0000FF;">()</span>
<!--</
Note the default behaviour, if set_test_verbosity() is not invoked, is no output and carry on as normal when all tests pass.<br>
Also note that set_test_pause() has no effect under pwa/p2js and the program will always carry on regardless of any failure, <br>
Line 1,738:
The '[http://software-lab.de/doc/refT.html#test test]' function is
built into PicoLisp.
<
(= (setq S (chop S)) (reverse S)) )
(test T (palindrome? "racecar"))
(test NIL (palindrome? "ferrari"))</
=={{header|Prolog}}==
Line 1,749:
It can also be run by using the run_tests predicate.
<
:- begin_tests(palindrome).
Line 1,756:
test(invalid_palindrome, [fail]) :- palindrome('this is not a palindrome').
:- end_tests(palindrome).</
=={{header|PureBasic}}==
PureBasic allows for definition of Assert() and other tools & the debugger is integrated into the native editor.
<
; Needed for the Assert-Macro below
" ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution!
Line 1,786:
text2$="wisconsin"
Assert(IsPalindrome(text1$), "Catching this would be a fail")
Assert(IsPalindrome(text2$), "Catching this is correct")</
=={{header|Python}}==
This uses the [[wp:doctest|doctest]] module from the Python standard library. This allows copies of tests run in an interactive session to be re-used as tests.
<
'''
>>> is_palindrome('')
Line 1,829:
if __name__ == "__main__":
_test()</
When run in the form as shown above there is no output as all tests pass. If the alternative doctest.testmod line is used with verbose=True, then the following output is produced:
Line 1,917:
See also the functions defineTestSuite and runTestSuite.
<
checkTrue(!palindroc("ab")) # TRUE
checkException(palindroc()) # TRUE
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function</
=={{header|Racket}}==
Line 1,926:
Racket has a built-in unit testing library. Tests can be specified next to function implementations or in a testing submodule.
<
#lang racket
(module+ test (require rackunit))
Line 1,943:
(check-true (palindromb "avoova"))
(check-false (palindromb "potato")))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
sub palin( Str $string) { so $string.lc.comb(/\w/) eq $string.flip.lc.comb(/\w/) }
Line 1,965:
is palin($test), $expected-result,
"\"$test\" is {$expected-result??''!!'not '}a palindrome.";
}</
Output:
Line 1,979:
Retro includes a library for creating automated tests. This is used for checking the standard libraries shipped with Retro.
<
needs hash'
Line 1,988:
: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion
: test ( - ) t0 t1 ;
test</
=={{header|REXX}}==
Line 1,995:
===stress REXX keywords (used as variables)===
{This was originally written in some form of FORTRAN.}
<
signal=(interpret=value); value=(interpret<parse); do upper=value to value; end
exit=upper*upper*upper*upper-value-upper; say=' '; return=say say say; with.=signal
Line 2,003:
say''say; end; do otherwise=value to then; pull=pull center(if.otherwise,,
length(return)); end; say pull; do otherwise=value to exit; with.otherwise=,
if.otherwise; end; end; exit 0 /*stick a fork in it, we're all done. */</
{{out|output|text=''':'''}}
<pre>
Line 2,023:
===stress test some REXX BIFs===
This stress tests some of the REXX built-in functions (BIFs).
<
z.=' '; z= 12-25-2002; y= z; w= -y
z.0= translate( right( time('c'), substr(z, 4, z==y)))
Line 2,043:
say z.32
say
exit 0 /*stick a fork in it, we're all done. */</
{{out|output|text=''':'''}}
<pre>
Line 2,054:
=={{header|Ring}}==
<
assert(IsPalindrome("racecar"))
assert(IsPalindrome("alice"))
</syntaxhighlight>
=={{header|Ruby}}==
Line 2,064:
Ruby comes with a unit testing package. All you have to do is to create a subclass of Test::Unit::Testcase that contains methods that begin with "test_". The package will create a test suite and run it for you.
<
s == s.reverse
end
Line 2,089:
assert(palindrome?("ab"), "this test case fails on purpose")
end
end</
<pre>$ ruby palindrome.rb
Line 2,109:
This example uses Minitest, which comes with Ruby 1.9. (But if you have Ruby 1.8, then you can still install Minitest as a gem, using [[:Category:RubyGems|RubyGems]].)
<
def palindrome?(s)
s == s.reverse
Line 2,136:
palindrome?("ab").must_equal true, "this test case fails on purpose"
end
end</
<pre>$ ruby19 palindrome.rb
Line 2,173:
its variants can be used instead.
<
/// codepoints, not graphemes).
///
Line 2,197:
assert!(is_palindrome("abba"));
}
}</
While unit tests are written together with the tested code (and thus may employ the
Line 2,210:
shown here, being similar to Haskell's QuickCheck.
<
import Prop._
import Gen._
Line 2,227:
forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) }
}</
Output:
Line 2,248:
SRFI 64 is a popular test library.
<
(import (srfi 64))
(test-begin "palindrome-tests")
Line 2,255:
(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions
(test-end)
</syntaxhighlight>
The library reports the number of pass/fail tests at the end; the report may be customised.
Line 2,263:
{{works with|Db2 LUW}}
{{libheader|db2unit}}
<
CREATE OR REPLACE PROCEDURE TEST_MY_TEST()
BEGIN
Line 2,273:
CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);
END @
</
Output:
<pre>
Line 2,311:
=={{header|Swift}}==
<
import XCTest
Line 2,342:
}
}
}</
=={{header|Tailspin}}==
<
templates palindrome
[$...] -> #
Line 2,355:
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
end 'palindrome filter'
</syntaxhighlight>
=={{header|Tcl}}==
Line 2,361:
{{libheader|tcltest}}
<
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’
Line 2,374:
} -returnCodes error -result "wrong # args: should be \"palindrome s\""
tcltest::cleanupTests</
If placed in a file called <tt>palindrome.test</tt>, the following output is produced when it is executed:
<pre>palindrome.test: Total 3 Passed 3 Skipped 0 Failed 0</pre>
Line 2,380:
=={{header|UNIX Shell}}==
<
is_palindrome() {
Line 2,393:
fi
}
</syntaxhighlight>
is_palindrome "A man, a plan, a canal, Panama!"
Line 2,401:
=={{header|VBA}}==
Using the StrReverse function after deleted spaces
<syntaxhighlight lang="vb">
Option Explicit
Line 2,417:
IsPalindrome = (tempTxt = StrReverse(tempTxt))
End Function
</syntaxhighlight>
{{out}}
<pre>abba is a palidrome ? True
Line 2,432:
=={{header|Wren}}==
{{libheader|Wren-test}}
<
var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
Line 2,451:
var reporter = ConsoleReporter.new()
TestPal.run(reporter)
reporter.epilogue()</
{{out}}
Line 2,470:
=={{header|zkl}}==
<
if (text.len()<2) return(False);
text==text.reverse();
}</
<
// spaces make this not a palindrome
tester.testRun(pali.fp("red rum sir is murder"), Void,False,__LINE__);</
Need to create a closure (.fp) so the unit test is what runs the test function and can catch any errors the test function throws.
{{output}}
Line 2,484:
</pre>
A test file:
<
fcn pali(text){
if (text.len()<2) return(False);
Line 2,494:
tester.stats();
returnClass(tester);</
<syntaxhighlight lang
{{output}}
<pre>
Line 2,510:
</pre>
If you had a collection of files to test:
<
{{output}}
<pre>
|