Test a function: Difference between revisions

Content added Content deleted
(Add Tailspin solution)
m (syntax highlighting fixup automation)
Line 13: Line 13:
Using [http://www.ccs.neu.edu/home/cce/acl2/doublecheck.html DoubleCheck]:
Using [http://www.ccs.neu.edu/home/cce/acl2/doublecheck.html DoubleCheck]:


<lang Lisp>(defun reverse-split-at-r (xs i ys)
<syntaxhighlight lang="lisp">(defun reverse-split-at-r (xs i ys)
(if (zp i)
(if (zp i)
(mv xs ys)
(mv xs ys)
Line 48: Line 48:
(defproperty palindrome-test
(defproperty palindrome-test
(p :value (random-palindrome))
(p :value (random-palindrome))
(is-palindrome p))</lang>
(is-palindrome p))</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Line 55: 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]
For larger testing frameworks, there are packages like [https://github.com/AdaCore/aunit Aunit] or [https://github.com/pyjarrett/trendy_test Trendy Test]


<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;


procedure Test_Function is
procedure Test_Function is
Line 82: Line 82:
Ada.Text_IO.Put_Line("Test Passed!");
Ada.Text_IO.Put_Line("Test Passed!");
end;
end;
end Test_Function;</lang>
end Test_Function;</syntaxhighlight>


Ada 2012 introduced a new way to specify functions and test their correctness: Pre- and Postoconditions.
Ada 2012 introduced a new way to specify functions and test their correctness: Pre- and Postoconditions.


<lang Ada> function Palindrome (Text : String) return Boolean
<syntaxhighlight lang="ada"> function Palindrome (Text : String) return Boolean
with Post => Palindrome'Result =
with Post => Palindrome'Result =
(Text'Length < 2 or else
(Text'Length < 2 or else
((Text(Text'First) = Text(Text'Last)) and then
((Text(Text'First) = Text(Text'Last)) and then
Palindrome(Text(Text'First+1 .. Text'Last-1))));</lang>
Palindrome(Text(Text'First+1 .. Text'Last-1))));</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>palindrome?: function [s][
<syntaxhighlight lang="rebol">palindrome?: function [s][
s = reverse s
s = reverse s
]
]
Line 103: Line 103:
]
]


loop tests => ensure</lang>
loop tests => ensure</syntaxhighlight>


{{out}}
{{out}}
Line 112: Line 112:
there is no "well known" testing library, but here is a simple testing framework: <br>
there is no "well known" testing library, but here is a simple testing framework: <br>
test library: assert.ahk
test library: assert.ahk
<lang AutoHotkey>; assert.ahk
<syntaxhighlight lang="autohotkey">; assert.ahk
;; assert(a, b, test=2)
;; assert(a, b, test=2)
assert(a, b="blank", test=0)
assert(a, b="blank", test=0)
Line 149: Line 149:


return 1
return 1
}</lang>
}</syntaxhighlight>
test example:
test example:
<lang AutoHotkey>assert(isPalindrome("in girum imus nocte et consumimur igni"), 1
<syntaxhighlight lang="autohotkey">assert(isPalindrome("in girum imus nocte et consumimur igni"), 1
, "palindrome test")
, "palindrome test")
assert(broken("in girum imus nocte et consumimur igni"), "works"
assert(broken("in girum imus nocte et consumimur igni"), "works"
Line 171: Line 171:


#Include assert.ahk
#Include assert.ahk
#Include palindrome.ahk</lang>
#Include palindrome.ahk</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>include :assert
<syntaxhighlight lang="brat">include :assert


palindrome? = { str |
palindrome? = { str |
Line 197: Line 197:
assert { palindrome? "blah blah" }
assert { palindrome? "blah blah" }
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 212: Line 212:
=={{header|C}}==
=={{header|C}}==


<lang C>#include <assert.h>
<syntaxhighlight lang="c">#include <assert.h>
int IsPalindrome(char *Str);
int IsPalindrome(char *Str);


Line 220: Line 220:
assert(IsPalindrome("alice"));
assert(IsPalindrome("alice"));
}
}
</syntaxhighlight>
</lang>


=={{header|C sharp}}==
=={{header|C sharp}}==
Line 226: Line 226:
First, using the VisualStudio TestTools for unit tests. I'm testing both of the methods for palindrome detection created in the article.
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">
<lang Csharp>
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PalindromeDetector.ConsoleApp;
using PalindromeDetector.ConsoleApp;
Line 260: Line 260:
}
}
}
}
}</lang>
}</syntaxhighlight>


Second, NUnit tests. Couldn't test these because of namespace issues with NUnit, but I'm sure they work.
Second, NUnit tests. Couldn't test these because of namespace issues with NUnit, but I'm sure they work.
<syntaxhighlight lang="csharp">
<lang Csharp>
using NUnit.Framework;
using NUnit.Framework;
using PalindromeDetector.ConsoleApp;
using PalindromeDetector.ConsoleApp;
Line 298: Line 298:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <string>
#include <string>


Line 308: Line 308:
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
}
</syntaxhighlight>
</lang>




Line 314: Line 314:
test can be tested at compile time - failing the test will cause a compilation failure.
test can be tested at compile time - failing the test will cause a compilation failure.


<lang cpp>void CompileTimeTests()
<syntaxhighlight lang="cpp">void CompileTimeTests()
{
{
static_assert(is_palindrome("ada"));
static_assert(is_palindrome("ada"));
Line 325: Line 325:
int main()
int main()
{
{
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 343: Line 343:
A popular testing framework is gtest.
A popular testing framework is gtest.


<lang cpp>#include <gtest/gtest.h>
<syntaxhighlight lang="cpp">#include <gtest/gtest.h>


TEST(PalindromeSuite, Test1)
TEST(PalindromeSuite, Test1)
Line 352: Line 352:
EXPECT_FALSE(is_palindrome("ada")); // will fail
EXPECT_FALSE(is_palindrome("ada")); // will fail
EXPECT_TRUE(is_palindrome("C++")); // will fail
EXPECT_TRUE(is_palindrome("C++")); // will fail
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 383: Line 383:
Boost also has a testing framework.
Boost also has a testing framework.


<lang cpp>#define BOOST_TEST_MAIN
<syntaxhighlight lang="cpp">#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test.hpp>


Line 393: Line 393:
BOOST_CHECK( is_palindrome("ada") == false); // will fail
BOOST_CHECK( is_palindrome("ada") == false); // will fail
BOOST_CHECK( is_palindrome("C++") == true); // will fail
BOOST_CHECK( is_palindrome("C++") == true); // will fail
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 404: Line 404:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(use 'clojure.test)
(use 'clojure.test)


Line 412: Line 412:


(run-tests)
(run-tests)
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(defpackage :rosetta
(defpackage :rosetta
(:use :cl
(:use :cl
Line 516: Line 516:
NIL
NIL
|#
|#
</syntaxhighlight>
</lang>


=={{header|Crystal}}==
=={{header|Crystal}}==


<lang ruby>require "spec"
<syntaxhighlight lang="ruby">require "spec"


describe "palindrome" do
describe "palindrome" do
Line 534: Line 534:
def palindrome(s)
def palindrome(s)
s == s.reverse
s == s.reverse
end</lang>
end</syntaxhighlight>


<pre>
<pre>
Line 542: Line 542:


=={{header|D}}==
=={{header|D}}==
<lang d>unittest {
<syntaxhighlight lang="d">unittest {
assert(isPalindrome("racecar"));
assert(isPalindrome("racecar"));
assert(isPalindrome("bob"));
assert(isPalindrome("bob"));
assert(!isPalindrome("alice"));
assert(!isPalindrome("alice"));
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 552: Line 552:
Using built in assertions.
Using built in assertions.


<lang Delphi> Assert(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
<syntaxhighlight lang="delphi"> Assert(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Assert(not IsPalindrome('123'), '123 is not a valid palindrome');</lang>
Assert(not IsPalindrome('123'), '123 is not a valid palindrome');</syntaxhighlight>


Using [[wp:DUnit|DUnit]], an open source unit testing framework that is bundled with Delphi.
Using [[wp:DUnit|DUnit]], an open source unit testing framework that is bundled with Delphi.


<lang Delphi> Check(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
<syntaxhighlight lang="delphi"> Check(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
Check(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Check(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Check(not IsPalindrome('123'), '123 is not a valid palindrome');</lang>
Check(not IsPalindrome('123'), '123 is not a valid palindrome');</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Line 568: 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.
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.


<lang e>#!/usr/bin/env rune
<syntaxhighlight lang="e">#!/usr/bin/env rune


? def isPalindrome(string :String) {
? def isPalindrome(string :String) {
Line 617: Line 617:


? (x + xreversed).size()
? (x + xreversed).size()
# value: 131072</lang>
# value: 131072</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
EchoLisp provides (assert <true-value?> ["fail-message"]) and (check-expect <expression> <expected-result>).
EchoLisp provides (assert <true-value?> ["fail-message"]) and (check-expect <expression> <expected-result>).
<lang lisp>
<syntaxhighlight lang="lisp">
(assert (palindrome? "aba")) → #t
(assert (palindrome? "aba")) → #t
(assert (palindrome? "abbbca") "palindrome fail")
(assert (palindrome? "abbbca") "palindrome fail")
Line 631: Line 631:
😐 warning: #t : check failed : (palindrome? abcda) → #f
😐 warning: #t : check failed : (palindrome? abcda) → #f
(assert (palindrome? "un roc lamina l animal cornu")) → #t
(assert (palindrome? "un roc lamina l animal cornu")) → #t
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
This is a unit test so I use Eunit. For system tests "Common Test" would be used. Both are built in.
This is a unit test so I use Eunit. For system tests "Common Test" would be used. Both are built in.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( palindrome_tests ).
-module( palindrome_tests ).
-compile( export_all ).
-compile( export_all ).
Line 643: Line 643:


abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 652: Line 652:
=={{header|Euphoria}}==
=={{header|Euphoria}}==


<lang euphoria>
<syntaxhighlight lang="euphoria">
--unittest in standard library 4.0+
--unittest in standard library 4.0+
include std/unittest.e
include std/unittest.e
Line 664: Line 664:
test_report()
test_report()


</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{libheader|NUnit}}
{{libheader|NUnit}}
<lang fsharp>let palindrome (s : string) =
<syntaxhighlight lang="fsharp">let palindrome (s : string) =
let a = s.ToUpper().ToCharArray()
let a = s.ToUpper().ToCharArray()
Array.rev a = a
Array.rev a = a
Line 683: Line 683:
[<Test>]
[<Test>]
member x.Test02() =
member x.Test02() =
Assert.IsFalse(palindrome "hello")</lang>
Assert.IsFalse(palindrome "hello")</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
Line 690: Line 690:
''palindrome/palindrome.factor''
''palindrome/palindrome.factor''


<lang factor>USING: kernel sequences ;
<syntaxhighlight lang="factor">USING: kernel sequences ;
IN: palindrome
IN: palindrome


: palindrome? ( string -- ? ) dup reverse = ;</lang>
: palindrome? ( string -- ? ) dup reverse = ;</syntaxhighlight>


''palindrome/palindrome-tests.factor''
''palindrome/palindrome-tests.factor''


<lang factor>USING: palindrome tools.test ;
<syntaxhighlight lang="factor">USING: palindrome tools.test ;
IN: palindrome.tests
IN: palindrome.tests


[ t ] [ "racecar" palindrome? ] unit-test
[ t ] [ "racecar" palindrome? ] unit-test
[ f ] [ "ferrari" palindrome? ] unit-test</lang>
[ f ] [ "ferrari" palindrome? ] unit-test</syntaxhighlight>


To run these tests from the listener:
To run these tests from the listener:


<lang factor>( scratchpad ) "palindrome" test</lang>
<syntaxhighlight lang="factor">( scratchpad ) "palindrome" test</syntaxhighlight>


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.
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: 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].
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].


<lang fantom>
<syntaxhighlight lang="fantom">
class TestPalindrome : Test
class TestPalindrome : Test
{
{
Line 727: Line 727:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 735: Line 735:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|VBA}}
{{trans|VBA}}
<lang freebasic>
<syntaxhighlight lang="freebasic">
Sub StrReverse(Byref text As String)
Sub StrReverse(Byref text As String)
Dim As Integer x, lt = Len(text)
Dim As Integer x, lt = Len(text)
Line 778: Line 778:
Next i
Next i
Sleep
Sleep
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 798: Line 798:
=={{header|Go}}==
=={{header|Go}}==
Using Go's standard command, go test.
Using Go's standard command, go test.
<lang go>package pal
<syntaxhighlight lang="go">package pal


import "testing"
import "testing"
Line 828: Line 828:
}
}
}
}
}</lang>
}</syntaxhighlight>
Output of go test:
Output of go test:
<pre>
<pre>
Line 839: 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.
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.


<lang haskell>import Test.QuickCheck
<syntaxhighlight lang="haskell">import Test.QuickCheck


isPalindrome :: String -> Bool
isPalindrome :: String -> Bool
Line 858: Line 858:
putStr "Odd palindromes: " >> quickCheck (\s -> not (null s) ==> isPalindrome (s ++ (tail.reverse) s))
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
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)))</lang>
==> not (isPalindrome (take i s ++ "•" ++ drop i s)))</syntaxhighlight>


The <code>==&gt;</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.
The <code>==&gt;</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: Line 868:
for failure. There is no standard framework, but the following example shows
for failure. There is no standard framework, but the following example shows
how these tests might be handled.
how these tests might be handled.
<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
s := "ablewasiereisawelba"
s := "ablewasiereisawelba"
assert{"test1",palindrome(s)}
assert{"test1",palindrome(s)}
Line 887: Line 887:
procedure assertFailure(A)
procedure assertFailure(A)
if @A[2] then write(@A[1],": failed")
if @A[2] then write(@A[1],": failed")
end</lang>
end</syntaxhighlight>


Which outputs:
Which outputs:
Line 901: Line 901:


Tests are contained in a test script <tt>c:\mypath\palindrome_test.ijs</tt> with the following contents:
Tests are contained in a test script <tt>c:\mypath\palindrome_test.ijs</tt> with the following contents:
<lang j>NB. Contents of palindrome_test.ijs
<syntaxhighlight lang="j">NB. Contents of palindrome_test.ijs


NB. Basic testing
NB. Basic testing
Line 916: Line 916:
test_palinB=: monad define
test_palinB=: monad define
assert isPalin0 'ab'
assert isPalin0 'ab'
)</lang>
)</syntaxhighlight>


Example Usage:
Example Usage:
<lang j> require 'general/unittest'
<syntaxhighlight lang="j"> require 'general/unittest'
unittest 'c:\mypath\palindrome_test.ijs'
unittest 'c:\mypath\palindrome_test.ijs'
Test: c:\mypath\palindrome_test.ijs
Test: c:\mypath\palindrome_test.ijs
palinA .................................. OK
palinA .................................. OK
palinB .................................. OK</lang>
palinB .................................. OK</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|5}}<br>
{{works with|Java|5}}<br>
{{libheader|JUnit}}
{{libheader|JUnit}}
<lang java5>import static ExampleClass.pali; // or from wherever it is defined
<syntaxhighlight lang="java5">import static ExampleClass.pali; // or from wherever it is defined
import static ExampleClass.rPali; // or from wherever it is defined
import static ExampleClass.rPali; // or from wherever it is defined
import org.junit.*;
import org.junit.*;
Line 975: Line 975:
//some code that should throw a WhateverException
//some code that should throw a WhateverException
}
}
}</lang>
}</syntaxhighlight>
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:
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:
<lang java5>public class RunTests{
<syntaxhighlight lang="java5">public class RunTests{
public static main(String[] args){
public static main(String[] args){
org.junit.runner.JUnitCore.runClasses(PalindromeTest.class/*, other classes here if you have more*/);
org.junit.runner.JUnitCore.runClasses(PalindromeTest.class/*, other classes here if you have more*/);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 990: Line 990:
{{works with|Browserify}}
{{works with|Browserify}}


<lang javascript>const assert = require('assert');
<syntaxhighlight lang="javascript">const assert = require('assert');


describe('palindrome', () => {
describe('palindrome', () => {
Line 1,013: Line 1,013:
});
});
})
})
});</lang>
});</syntaxhighlight>


Output:
Output:
Line 1,053: Line 1,053:


Here is an example of a file with four test case triplets:
Here is an example of a file with four test case triplets:
<lang sh># Test case 1:
<syntaxhighlight lang="sh"># Test case 1:
.
.
1
1
Line 1,071: Line 1,071:
def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial
def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial
3
3
6</lang>
6</syntaxhighlight>


If the file is named, say, test.txt, then the tests can be run by executing: jq --run-tests < test.txt
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:
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:
<lang sh>$ jq --run-tests < jq.tests
<syntaxhighlight lang="sh">$ jq --run-tests < jq.tests


Testing '.' at line number 3
Testing '.' at line number 3
Line 1,084: Line 1,084:
Testing 'def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial' at line number 18
Testing 'def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial' at line number 18
3 of 4 tests passed (0 malformed)
3 of 4 tests passed (0 malformed)
</syntaxhighlight>
</lang>
===Testing jq Libraries===
===Testing jq Libraries===


Line 1,092: Line 1,092:
For example, suppose the file library.jq contains the following definitions:
For example, suppose the file library.jq contains the following definitions:


<lang jq>def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end;
<syntaxhighlight lang="jq">def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end;


def palindrome: explode as $in | ($in|reverse) == $in;</lang>
def palindrome: explode as $in | ($in|reverse) == $in;</syntaxhighlight>


and that the file test-library.txt contains the two test triplets:
and that the file test-library.txt contains the two test triplets:


<lang sh>import "library" as lib; lib::factorial
<syntaxhighlight lang="sh">import "library" as lib; lib::factorial
3
3
6
6
Line 1,104: Line 1,104:
import "library" as lib; lib::palindrome
import "library" as lib; lib::palindrome
"salàlas"
"salàlas"
true</lang>
true</syntaxhighlight>


Then the tests can be run by invoking jq in the usual way:
Then the tests can be run by invoking jq in the usual way:
<lang sh>jq --run-tests < test-library.txt</lang>
<syntaxhighlight lang="sh">jq --run-tests < test-library.txt</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
Line 1,115: Line 1,115:
Given the [[Palindrome detection]] solution of
Given the [[Palindrome detection]] solution of


<lang javascript>/* Palindrome detection, in Jsish */
<syntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
if (!exact) {
Line 1,121: Line 1,121:
}
}
return str === str.split('').reverse().join('');
return str === str.split('').reverse().join('');
}</lang>
}</syntaxhighlight>


''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)
''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: 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.
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.


<lang javascript>/* Palindrome detection, in Jsish */
<syntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
if (!exact) {
Line 1,154: Line 1,154:
isPalindrome('CUB') ==> false
isPalindrome('CUB') ==> false
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


Giving
Giving
Line 1,179: 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).
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).


<lang javascript>/* Palindrome detection, in Jsish */
<syntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
if (!exact) {
Line 1,201: Line 1,201:
isPalindrome('CUB') ==> false
isPalindrome('CUB') ==> false
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


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:
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: Line 1,210:
Which now looks like
Which now looks like


<lang javascript>/* Palindrome detection, in Jsish */
<syntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
if (!exact) {
Line 1,238: Line 1,238:
isPalindrome('A man, a plan, a canal; Panama!', true) ==> false
isPalindrome('A man, a plan, a canal; Panama!', true) ==> false
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


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.
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: 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.
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.


<lang javascript>/* Interaction testing */
<syntaxhighlight lang="javascript">/* Interaction testing */
var trial = console.input();
var trial = console.input();
puts(trial.replace(/a/g, 'b'));
puts(trial.replace(/a/g, 'b'));
Line 1,258: Line 1,258:
bbccbb
bbccbb
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


{{out}}
{{out}}
Line 1,280: Line 1,280:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>using Base.Test
<syntaxhighlight lang="julia">using Base.Test
include("Palindrome_detection.jl")
include("Palindrome_detection.jl")


Line 1,299: Line 1,299:
@test !palindrome("a11")
@test !palindrome("a11")
@test !palindrome("012")
@test !palindrome("012")
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 1,309: Line 1,309:
=={{header|Kotlin}}==
=={{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:
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:
<lang scala>// version 1.1.3
<syntaxhighlight lang="scala">// version 1.1.3


fun isPalindrome(s: String) = (s == s.reversed())
fun isPalindrome(s: String) = (s == s.reversed())
Line 1,323: Line 1,323:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,334: Line 1,334:
The following example uses the [https://bitbucket.org/bfad/lspec/ LSpec Library]:
The following example uses the [https://bitbucket.org/bfad/lspec/ LSpec Library]:


<lang lasso>// Taken from the Lasso entry in Palindrome page
<syntaxhighlight lang="lasso">// Taken from the Lasso entry in Palindrome page
define isPalindrome(text::string) => {
define isPalindrome(text::string) => {
Line 1,370: Line 1,370:
// Run the tests and get the summary
// Run the tests and get the summary
// (This normally isn't in the code as the test suite is run via command-line.)
// (This normally isn't in the code as the test suite is run via command-line.)
lspec->stop</lang>
lspec->stop</syntaxhighlight>


{{out}}
{{out}}
Line 1,379: Line 1,379:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>assert( ispalindrome("ABCBA") )
<syntaxhighlight lang="lua">assert( ispalindrome("ABCBA") )
assert( ispalindrome("ABCDE") )</lang>
assert( ispalindrome("ABCDE") )</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]]
<syntaxhighlight lang="mathematica">myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]]
On[Assert];myFun[1.0]</lang>
On[Assert];myFun[1.0]</syntaxhighlight>
{{out}}
{{out}}
<pre>Assert::asrtf: Assertion y>5 failed.
<pre>Assert::asrtf: Assertion y>5 failed.
Line 1,391: Line 1,391:
=={{header|NetRexx}}==
=={{header|NetRexx}}==
{{libheader|JUnit}}
{{libheader|JUnit}}
<lang NetRExx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary
Line 1,434: Line 1,434:


return
return
</syntaxhighlight>
</lang>
;Output
;Output
<pre>
<pre>
Line 1,446: Line 1,446:
=={{header|Nim}}==
=={{header|Nim}}==
Using assertions (no output means all tests were correct; this only works with debug builds!):
Using assertions (no output means all tests were correct; this only works with debug builds!):
<lang nim>proc reversed(s: string): string =
<syntaxhighlight lang="nim">proc reversed(s: string): string =
result = newString(s.len)
result = newString(s.len)
for i, c in s:
for i, c in s:
Line 1,463: Line 1,463:
assert(not isPalindrome("ba_ ab"))
assert(not isPalindrome("ba_ ab"))
assert(isPalindrome("ba _ ab"))
assert(isPalindrome("ba _ ab"))
assert(not isPalindrome("abab"))</lang>
assert(not isPalindrome("abab"))</syntaxhighlight>


Using the “unittest” module:
Using the “unittest” module:
<lang nim>import unittest
<syntaxhighlight lang="nim">import unittest


proc reversed(s: string): string =
proc reversed(s: string): string =
Line 1,491: Line 1,491:


test "no palindrome":
test "no palindrome":
check isPalindrome("foo") == false</lang>
check isPalindrome("foo") == false</syntaxhighlight>


{{out}}:
{{out}}:
Line 1,511: Line 1,511:
ocaml unix.cma -I +oUnit oUnit.cma palindrome.cmo palindrome_tests.ml
ocaml unix.cma -I +oUnit oUnit.cma palindrome.cmo palindrome_tests.ml


<lang ocaml>open OUnit
<syntaxhighlight lang="ocaml">open OUnit
open Palindrome
open Palindrome


Line 1,536: Line 1,536:
"test_palindrome_5" >:: test_palindrome_5]
"test_palindrome_5" >:: test_palindrome_5]
let _ =
let _ =
run_test_tt_main suite</lang>
run_test_tt_main suite</syntaxhighlight>


=={{header|Oforth}}==
=={{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 :
Unit tests are a built-in functionality. If Oforth is run using --t option, all tests are checked. Otherwise, tests are not checked :
<lang Oforth>test: [ "abcd" isPalindrome ]
<syntaxhighlight lang="oforth">test: [ "abcd" isPalindrome ]
test: ["abba" isPalindrome ]
test: ["abba" isPalindrome ]
test: [ "abcba" isPalindrome ]</lang>
test: [ "abcba" isPalindrome ]</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,561: Line 1,561:
{{trans|Raku}}
{{trans|Raku}}


<lang perl># ptest.t
<syntaxhighlight lang="perl"># ptest.t
use strict;
use strict;
use warnings;
use warnings;
Line 1,597: Line 1,597:
ok palindrome_r == $expect, 1, "palindrome_r: $note";
ok palindrome_r == $expect, 1, "palindrome_r: $note";
ok palindrome_e == $expect, 1, "palindrome_e: $note";
ok palindrome_e == $expect, 1, "palindrome_e: $note";
}</lang>
}</syntaxhighlight>


The program produces TAP output.
The program produces TAP output.
Line 1,652: Line 1,652:
{{libheader|Phix/basics}}
{{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.
The only golden rule here is to invoke test_summary() after any [block of] tests have been run, everything else is optional.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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: Line 1,682:
<span style="color: #7060A8;">test_summary</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">test_summary</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
Note the default behaviour, if set_test_verbosity() is not invoked, is no output and carry on as normal when all tests pass.<br>
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>
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: Line 1,738:
The '[http://software-lab.de/doc/refT.html#test test]' function is
The '[http://software-lab.de/doc/refT.html#test test]' function is
built into PicoLisp.
built into PicoLisp.
<lang PicoLisp>(de palindrome? (S)
<syntaxhighlight lang="picolisp">(de palindrome? (S)
(= (setq S (chop S)) (reverse S)) )
(= (setq S (chop S)) (reverse S)) )


(test T (palindrome? "racecar"))
(test T (palindrome? "racecar"))
(test NIL (palindrome? "ferrari"))</lang>
(test NIL (palindrome? "ferrari"))</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
Line 1,749: Line 1,749:
It can also be run by using the run_tests predicate.
It can also be run by using the run_tests predicate.


<lang Prolog>palindrome(Word) :- name(Word,List), reverse(List,List).
<syntaxhighlight lang="prolog">palindrome(Word) :- name(Word,List), reverse(List,List).


:- begin_tests(palindrome).
:- begin_tests(palindrome).
Line 1,756: Line 1,756:
test(invalid_palindrome, [fail]) :- palindrome('this is not a palindrome').
test(invalid_palindrome, [fail]) :- palindrome('this is not a palindrome').


:- end_tests(palindrome).</lang>
:- end_tests(palindrome).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic allows for definition of Assert() and other tools & the debugger is integrated into the native editor.
PureBasic allows for definition of Assert() and other tools & the debugger is integrated into the native editor.
<lang PureBasic>Macro DoubleQuote
<syntaxhighlight lang="purebasic">Macro DoubleQuote
; Needed for the Assert-Macro below
; Needed for the Assert-Macro below
" ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution!
" ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution!
Line 1,786: Line 1,786:
text2$="wisconsin"
text2$="wisconsin"
Assert(IsPalindrome(text1$), "Catching this would be a fail")
Assert(IsPalindrome(text1$), "Catching this would be a fail")
Assert(IsPalindrome(text2$), "Catching this is correct")</lang>
Assert(IsPalindrome(text2$), "Catching this is correct")</syntaxhighlight>


=={{header|Python}}==
=={{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.
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.


<lang python>def is_palindrome(s):
<syntaxhighlight lang="python">def is_palindrome(s):
'''
'''
>>> is_palindrome('')
>>> is_palindrome('')
Line 1,829: Line 1,829:


if __name__ == "__main__":
if __name__ == "__main__":
_test()</lang>
_test()</syntaxhighlight>
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:
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: Line 1,917:


See also the functions defineTestSuite and runTestSuite.
See also the functions defineTestSuite and runTestSuite.
<lang r>checkTrue(palindroc("aba")) # TRUE
<syntaxhighlight lang="r">checkTrue(palindroc("aba")) # TRUE
checkTrue(!palindroc("ab")) # TRUE
checkTrue(!palindroc("ab")) # TRUE
checkException(palindroc()) # TRUE
checkException(palindroc()) # TRUE
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function</lang>
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,926: Line 1,926:
Racket has a built-in unit testing library. Tests can be specified next to function implementations or in a testing submodule.
Racket has a built-in unit testing library. Tests can be specified next to function implementations or in a testing submodule.


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(module+ test (require rackunit))
(module+ test (require rackunit))
Line 1,943: Line 1,943:
(check-true (palindromb "avoova"))
(check-true (palindromb "avoova"))
(check-false (palindromb "potato")))
(check-false (palindromb "potato")))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>use Test;
<syntaxhighlight lang="raku" line>use Test;


sub palin( Str $string) { so $string.lc.comb(/\w/) eq $string.flip.lc.comb(/\w/) }
sub palin( Str $string) { so $string.lc.comb(/\w/) eq $string.flip.lc.comb(/\w/) }
Line 1,965: Line 1,965:
is palin($test), $expected-result,
is palin($test), $expected-result,
"\"$test\" is {$expected-result??''!!'not '}a palindrome.";
"\"$test\" is {$expected-result??''!!'not '}a palindrome.";
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,979: Line 1,979:
Retro includes a library for creating automated tests. This is used for checking the standard libraries shipped with Retro.
Retro includes a library for creating automated tests. This is used for checking the standard libraries shipped with Retro.


<lang Retro>needs assertion'
<syntaxhighlight lang="retro">needs assertion'
needs hash'
needs hash'


Line 1,988: Line 1,988:
: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion
: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion
: test ( - ) t0 t1 ;
: test ( - ) t0 t1 ;
test</lang>
test</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,995: Line 1,995:
===stress REXX keywords (used as variables)===
===stress REXX keywords (used as variables)===
{This was originally written in some form of FORTRAN.}
{This was originally written in some form of FORTRAN.}
<lang rexx>/*REXX program stresses various REXX functions (BIFs), many BIFs are used as variables. */
<syntaxhighlight lang="rexx">/*REXX program stresses various REXX functions (BIFs), many BIFs are used as variables. */
signal=(interpret=value); value=(interpret<parse); do upper=value to value; end
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
exit=upper*upper*upper*upper-value-upper; say=' '; return=say say say; with.=signal
Line 2,003: Line 2,003:
say''say; end; do otherwise=value to then; pull=pull center(if.otherwise,,
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=,
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. */</lang>
if.otherwise; end; end; exit 0 /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=''':'''}}
{{out|output|text=''':'''}}
<pre>
<pre>
Line 2,023: Line 2,023:
===stress test some REXX BIFs===
===stress test some REXX BIFs===
This stress tests some of the REXX built-in functions (BIFs).
This stress tests some of the REXX built-in functions (BIFs).
<lang rexx>/*REXX program shows a secret message to the terminal by using REXX built─in functions. */
<syntaxhighlight lang="rexx">/*REXX program shows a secret message to the terminal by using REXX built─in functions. */
z.=' '; z= 12-25-2002; y= z; w= -y
z.=' '; z= 12-25-2002; y= z; w= -y
z.0= translate( right( time('c'), substr(z, 4, z==y)))
z.0= translate( right( time('c'), substr(z, 4, z==y)))
Line 2,043: Line 2,043:
say z.32
say z.32
say
say
exit 0 /*stick a fork in it, we're all done. */</lang>
exit 0 /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=''':'''}}
{{out|output|text=''':'''}}
<pre>
<pre>
Line 2,054: Line 2,054:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
assert(IsPalindrome("racecar"))
assert(IsPalindrome("racecar"))
assert(IsPalindrome("alice"))
assert(IsPalindrome("alice"))
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
Line 2,064: 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.
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.


<lang ruby>def palindrome?(s)
<syntaxhighlight lang="ruby">def palindrome?(s)
s == s.reverse
s == s.reverse
end
end
Line 2,089: Line 2,089:
assert(palindrome?("ab"), "this test case fails on purpose")
assert(palindrome?("ab"), "this test case fails on purpose")
end
end
end</lang>
end</syntaxhighlight>


<pre>$ ruby palindrome.rb
<pre>$ ruby palindrome.rb
Line 2,109: 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]].)
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]].)


<lang ruby># palindrome.rb
<syntaxhighlight lang="ruby"># palindrome.rb
def palindrome?(s)
def palindrome?(s)
s == s.reverse
s == s.reverse
Line 2,136: Line 2,136:
palindrome?("ab").must_equal true, "this test case fails on purpose"
palindrome?("ab").must_equal true, "this test case fails on purpose"
end
end
end</lang>
end</syntaxhighlight>


<pre>$ ruby19 palindrome.rb
<pre>$ ruby19 palindrome.rb
Line 2,173: Line 2,173:
its variants can be used instead.
its variants can be used instead.


<lang Rust>/// Tests if the given string slice is a palindrome (with the respect to
<syntaxhighlight lang="rust">/// Tests if the given string slice is a palindrome (with the respect to
/// codepoints, not graphemes).
/// codepoints, not graphemes).
///
///
Line 2,197: Line 2,197:
assert!(is_palindrome("abba"));
assert!(is_palindrome("abba"));
}
}
}</lang>
}</syntaxhighlight>


While unit tests are written together with the tested code (and thus may employ the
While unit tests are written together with the tested code (and thus may employ the
Line 2,210: Line 2,210:
shown here, being similar to Haskell's QuickCheck.
shown here, being similar to Haskell's QuickCheck.


<lang scala>import org.scalacheck._
<syntaxhighlight lang="scala">import org.scalacheck._
import Prop._
import Prop._
import Gen._
import Gen._
Line 2,227: Line 2,227:
forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) }
forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) }
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 2,248: Line 2,248:
SRFI 64 is a popular test library.
SRFI 64 is a popular test library.


<lang scheme>
<syntaxhighlight lang="scheme">
(import (srfi 64))
(import (srfi 64))
(test-begin "palindrome-tests")
(test-begin "palindrome-tests")
Line 2,255: Line 2,255:
(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions
(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions
(test-end)
(test-end)
</syntaxhighlight>
</lang>


The library reports the number of pass/fail tests at the end; the report may be customised.
The library reports the number of pass/fail tests at the end; the report may be customised.
Line 2,263: Line 2,263:
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
{{libheader|db2unit}}
{{libheader|db2unit}}
<lang sql pl>
<syntaxhighlight lang="sql pl">
CREATE OR REPLACE PROCEDURE TEST_MY_TEST()
CREATE OR REPLACE PROCEDURE TEST_MY_TEST()
BEGIN
BEGIN
Line 2,273: Line 2,273:
CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);
CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);
END @
END @
</lang>
</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 2,311: Line 2,311:


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Cocoa
<syntaxhighlight lang="swift">import Cocoa
import XCTest
import XCTest


Line 2,342: Line 2,342:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
templates palindrome
templates palindrome
[$...] -> #
[$...] -> #
Line 2,355: Line 2,355:
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
end 'palindrome filter'
end 'palindrome filter'
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 2,361: Line 2,361:


{{libheader|tcltest}}
{{libheader|tcltest}}
<lang tcl>package require tcltest 2
<syntaxhighlight lang="tcl">package require tcltest 2
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’


Line 2,374: Line 2,374:
} -returnCodes error -result "wrong # args: should be \"palindrome s\""
} -returnCodes error -result "wrong # args: should be \"palindrome s\""


tcltest::cleanupTests</lang>
tcltest::cleanupTests</syntaxhighlight>
If placed in a file called <tt>palindrome.test</tt>, the following output is produced when it is executed:
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>
<pre>palindrome.test: Total 3 Passed 3 Skipped 0 Failed 0</pre>
Line 2,380: Line 2,380:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang sh>#!/bin/bash
<syntaxhighlight lang="sh">#!/bin/bash


is_palindrome() {
is_palindrome() {
Line 2,393: Line 2,393:
fi
fi
}
}
</syntaxhighlight>
</lang>


is_palindrome "A man, a plan, a canal, Panama!"
is_palindrome "A man, a plan, a canal, Panama!"
Line 2,401: Line 2,401:
=={{header|VBA}}==
=={{header|VBA}}==
Using the StrReverse function after deleted spaces
Using the StrReverse function after deleted spaces
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 2,417: Line 2,417:
IsPalindrome = (tempTxt = StrReverse(tempTxt))
IsPalindrome = (tempTxt = StrReverse(tempTxt))
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>abba is a palidrome ? True
<pre>abba is a palidrome ? True
Line 2,432: Line 2,432:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-test}}
{{libheader|Wren-test}}
<lang ecmascript>import "/module" for Expect, Suite, ConsoleReporter
<syntaxhighlight lang="ecmascript">import "/module" for Expect, Suite, ConsoleReporter


var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
Line 2,451: Line 2,451:
var reporter = ConsoleReporter.new()
var reporter = ConsoleReporter.new()
TestPal.run(reporter)
TestPal.run(reporter)
reporter.epilogue()</lang>
reporter.epilogue()</syntaxhighlight>


{{out}}
{{out}}
Line 2,470: Line 2,470:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn pali(text){
<syntaxhighlight lang="zkl">fcn pali(text){
if (text.len()<2) return(False);
if (text.len()<2) return(False);
text==text.reverse();
text==text.reverse();
}</lang>
}</syntaxhighlight>
<lang zkl>tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
<syntaxhighlight lang="zkl">tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
// spaces make this not a palindrome
// spaces make this not a palindrome
tester.testRun(pali.fp("red rum sir is murder"), Void,False,__LINE__);</lang>
tester.testRun(pali.fp("red rum sir is murder"), Void,False,__LINE__);</syntaxhighlight>
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.
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}}
{{output}}
Line 2,484: Line 2,484:
</pre>
</pre>
A test file:
A test file:
<lang zkl>tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
<syntaxhighlight lang="zkl">tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
fcn pali(text){
fcn pali(text){
if (text.len()<2) return(False);
if (text.len()<2) return(False);
Line 2,494: Line 2,494:


tester.stats();
tester.stats();
returnClass(tester);</lang>
returnClass(tester);</syntaxhighlight>
<lang zkl>zkl paliTest.zkl</lang>
<syntaxhighlight lang="zkl">zkl paliTest.zkl</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>
Line 2,510: Line 2,510:
</pre>
</pre>
If you had a collection of files to test:
If you had a collection of files to test:
<lang zkl>zkl Test.testThemAll -- paliTest.zkl</lang>
<syntaxhighlight lang="zkl">zkl Test.testThemAll -- paliTest.zkl</syntaxhighlight>
{{output}}
{{output}}
<pre>
<pre>