Test a function: Difference between revisions

Add bruijn
m (→‎{{header|Phix}}: better descs)
(Add bruijn)
 
(30 intermediate revisions by 17 users not shown)
Line 1:
{{task|Testing}}{{omit from|BBC BASIC}}
 
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in [[Palindrome]]. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
{{omit from|BBC BASIC}}
 
 
;Task:
Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in [[Palindrome]].
 
If your language does not have a testing specific library well known to the language's community then state this or omit the language.<br><br>
 
=={{header|ACL2}}==
Line 6 ⟶ 13:
Using [http://www.ccs.neu.edu/home/cce/acl2/doublecheck.html DoubleCheck]:
 
<langsyntaxhighlight Lisplang="lisp">(defun reverse-split-at-r (xs i ys)
(if (zp i)
(mv xs ys)
Line 41 ⟶ 48:
(defproperty palindrome-test
(p :value (random-palindrome))
(is-palindrome p))</langsyntaxhighlight>
 
=={{header|Ada}}==
 
For normal use there is pragma Assert, functioning the same as many other languages.<br>
For larger testing frameworks, there are packages like [httphttps://libre.adacoregithub.com/libre/toolsAdaCore/aunit/ Aunit] or [https://github.com/pyjarrett/trendy_test Trendy Test]
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Test_Function is
Line 75 ⟶ 82:
Ada.Text_IO.Put_Line("Test Passed!");
end;
end Test_Function;</langsyntaxhighlight>
 
Ada 2012 introduced a new way to specify functions and test their correctness: Pre- and Postoconditions.
 
<langsyntaxhighlight Adalang="ada"> function Palindrome (Text : String) return Boolean
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))));</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">palindrome?: function [s][
s = reverse s
]
 
tests: [
[true? palindrome? "aba"]
[false? palindrome? "ab" ]
]
 
loop tests => ensure</syntaxhighlight>
 
{{out}}
 
<pre></pre>
 
=={{header|AutoHotkey}}==
there is no "well known" testing library, but here is a simple testing framework: <br>
test library: assert.ahk
<langsyntaxhighlight AutoHotkeylang="autohotkey">; assert.ahk
;; assert(a, b, test=2)
assert(a, b="blank", test=0)
Line 125 ⟶ 149:
 
return 1
}</langsyntaxhighlight>
test example:
<langsyntaxhighlight AutoHotkeylang="autohotkey">assert(isPalindrome("in girum imus nocte et consumimur igni"), 1
, "palindrome test")
assert(broken("in girum imus nocte et consumimur igni"), "works"
Line 147 ⟶ 171:
 
#Include assert.ahk
#Include palindrome.ahk</langsyntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :assert
 
palindrome? = { str |
Line 173 ⟶ 197:
assert { palindrome? "blah blah" }
}
}</langsyntaxhighlight>
 
Output:
Line 185 ⟶ 209:
 
4 tests, 4 assertions, 1 failures.</pre>
 
=={{header|Bruijn}}==
Bruijn has equivalency testing builtin. The <code>:test</code> instruction checks whether two terms are beta-equivalent (alpha-equivalent after beta-reduction) and prints an error if they aren't. Alpha-conversion is not needed because of the usage of De Bruijn indices. All tests in imported files get run automatically (can be disabled using a CLI flag).
<syntaxhighlight lang="bruijn">
:import std/String .
 
main [<~>0 =? 0]
 
:test (main "tacocat") ([[1]])
:test (main "bruijn") ([[1]])
</syntaxhighlight>
 
{{out}}
<pre>
ERROR test failed: (main [((0 [[[(0 (1 (0 (0 (0 (1 (1 (0 2))))))))]]]) [((0 [[[(0 (1 (0 (0 (1 (1 (1 (0 2))))))))]]]) [((0 [[[(1 (0 (1 (0 (1 (1 (1 (0 2))))))))]]]) [((0 [[[(1 (0 (0 (1 (0 (1 (1 (0 2))))))))]]]) [((0 [[[(0 (1 (0 (1 (0 (1 (1 (0 2))))))))]]]) [((0 [[[(0 (1 (1 (1 (0 (1 (1 (0 2))))))))]]]) [[0]])])])])])])]) = [[1]]
reduced to [[0]] = [[1]]
</pre>
 
=={{header|C}}==
 
<langsyntaxhighlight Clang="c">#include <assert.h>
int IsPalindrome(char *Str);
 
Line 196 ⟶ 237:
assert(IsPalindrome("alice"));
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp}}==
Line 202 ⟶ 243:
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 PalindromeDetector.ConsoleApp;
Line 236 ⟶ 277:
}
}
}</langsyntaxhighlight>
 
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 PalindromeDetector.ConsoleApp;
Line 274 ⟶ 315:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <algorithm>
#include <string>
 
constexpr bool is_palindrome(std::string_view s)
{
return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
</syntaxhighlight>
 
 
C++ has several popular frameworks for testing. However, simple things like a palidrome
test can be tested at compile time - failing the test will cause a compilation failure.
 
<syntaxhighlight lang="cpp">void CompileTimeTests()
{
static_assert(is_palindrome("ada"));
static_assert(!is_palindrome("C++"));
 
static_assert(is_palindrome("C++")); // fails at compile time
static_assert(!is_palindrome("ada")); // fails at compile time
}
 
int main()
{
}</syntaxhighlight>
{{out}}
<pre>
/home/garbanzo/play/rosettascratch/test-a-function_constexpr.cpp: In function 'void CompileTimeTests()':
/home/garbanzo/play/rosettascratch/test-a-function_constexpr.cpp:18:30: error: static assertion failed
18 | static_assert(is_palindrome("C++")); // fails at compile time
| ~~~~~~~~~~~~~^~~~~~~
/home/garbanzo/play/rosettascratch/test-a-function_constexpr.cpp:19:17: error: static assertion failed
19 | static_assert(!is_palindrome("ada")); // fails at compile time
| ^~~~~~~~~~~~~~~~~~~~~
gmake[2]: *** [CMakeFiles/scratch.dir/build.make:286: CMakeFiles/scratch.dir/test-a-function_constexpr.cpp.o] Error 1
gmake[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/scratch.dir/all] Error 2
gmake: *** [Makefile:136: all] Error 2
</pre>
 
 
A popular testing framework is gtest.
 
<syntaxhighlight lang="cpp">#include <gtest/gtest.h>
 
TEST(PalindromeSuite, Test1)
{
EXPECT_TRUE(is_palindrome("ada"));
EXPECT_FALSE(is_palindrome("C++"));
 
EXPECT_FALSE(is_palindrome("ada")); // will fail
EXPECT_TRUE(is_palindrome("C++")); // will fail
}</syntaxhighlight>
{{out}}
<pre>
Running main() from /var/tmp/portage/dev-cpp/gtest-1.11.0/work/googletest-release-1.11.0/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from PalindromeSuite
[ RUN ] PalindromeSuite.Test1
/home/garbanzo/play/rosettascratch/test-a-function_gtest.cpp:16: Failure
Value of: is_palindrome("ada")
Actual: true
Expected: false
/home/garbanzo/play/rosettascratch/test-a-function_gtest.cpp:17: Failure
Value of: is_palindrome("C++")
Actual: false
Expected: true
[ FAILED ] PalindromeSuite.Test1 (0 ms)
[----------] 1 test from PalindromeSuite (0 ms total)
 
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] PalindromeSuite.Test1
 
1 FAILED TEST
</pre>
 
 
Boost also has a testing framework.
 
<syntaxhighlight lang="cpp">#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
 
BOOST_AUTO_TEST_CASE( Test1 )
{
BOOST_CHECK( is_palindrome("ada") == true );
BOOST_CHECK( is_palindrome("C++") == false );
 
BOOST_CHECK( is_palindrome("ada") == false); // will fail
BOOST_CHECK( is_palindrome("C++") == true); // will fail
}</syntaxhighlight>
{{out}}
<pre>
Running 1 test case...
[path]/test-a-function_boost.cpp(20): error: in "Test1": check is_palindrome("ada") == false has failed
[path]/test-a-function_boost.cpp(21): error: in "Test1": check is_palindrome("C++") == true has failed
 
*** 2 failures are detected in the test module "Master Test Suite"
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">
(use 'clojure.test)
 
(deftest test-palindrome?
(is (= true (palindrome? "amanaplanacanalpanama")))
(is (= falsenot (palindrome? "Test 1, 2, 3"))))
 
(run-tests)
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">
(defpackage :rosetta
(:use :cl
Line 389 ⟶ 533:
NIL
|#
</syntaxhighlight>
</lang>
 
=={{header|Crystal}}==
 
<langsyntaxhighlight lang="ruby">require "spec"
 
describe "palindrome" do
Line 407 ⟶ 551:
def palindrome(s)
s == s.reverse
end</langsyntaxhighlight>
 
<pre>
Line 415 ⟶ 559:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">unittest {
assert(isPalindrome("racecar"));
assert(isPalindrome("bob"));
assert(!isPalindrome("alice"));
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 425 ⟶ 569:
Using built in assertions.
 
<langsyntaxhighlight Delphilang="delphi"> Assert(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
Assert(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Assert(not IsPalindrome('123'), '123 is not a valid palindrome');</langsyntaxhighlight>
 
Using [[wp:DUnit|DUnit]], an open source unit testing framework that is bundled with Delphi.
 
<langsyntaxhighlight Delphilang="delphi"> Check(IsPalindrome('salàlas'), 'salàlas is a valid palindrome');
Check(IsPalindrome('Ingirumimusnocteetconsumimurigni'), 'Ingirumimusnocteetconsumimurigni is a valid palindrome');
Check(not IsPalindrome('123'), '123 is not a valid palindrome');</langsyntaxhighlight>
 
=={{header|E}}==
Line 441 ⟶ 585:
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.
 
<langsyntaxhighlight lang="e">#!/usr/bin/env rune
 
? def isPalindrome(string :String) {
Line 490 ⟶ 634:
 
? (x + xreversed).size()
# value: 131072</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
EchoLisp provides (assert <true-value?> ["fail-message"]) and (check-expect <expression> <expected-result>).
<langsyntaxhighlight lang="lisp">
(assert (palindrome? "aba")) → #t
(assert (palindrome? "abbbca") "palindrome fail")
Line 504 ⟶ 648:
😐 warning: #t : check failed : (palindrome? abcda) → #f
(assert (palindrome? "un roc lamina l animal cornu")) → #t
</syntaxhighlight>
</lang>
 
=={{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">
<lang Erlang>
-module( palindrome_tests ).
-compile( export_all ).
Line 516 ⟶ 660:
 
abcdef_test() -> ?assertNot( palindrome:is_palindrome("abcdef") ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 525 ⟶ 669:
=={{header|Euphoria}}==
 
<langsyntaxhighlight lang="euphoria">
--unittest in standard library 4.0+
include std/unittest.e
Line 537 ⟶ 681:
test_report()
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
{{libheader|NUnit}}
<langsyntaxhighlight lang="fsharp">let palindrome (s : string) =
let a = s.ToUpper().ToCharArray()
Array.rev a = a
Line 556 ⟶ 700:
[<Test>]
member x.Test02() =
Assert.IsFalse(palindrome "hello")</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 563 ⟶ 707:
''palindrome/palindrome.factor''
 
<langsyntaxhighlight lang="factor">USING: kernel sequences ;
IN: palindrome
 
: palindrome? ( string -- ? ) dup reverse = ;</langsyntaxhighlight>
 
''palindrome/palindrome-tests.factor''
 
<langsyntaxhighlight lang="factor">USING: palindrome tools.test ;
IN: palindrome.tests
 
[ t ] [ "racecar" palindrome? ] unit-test
[ f ] [ "ferrari" palindrome? ] unit-test</langsyntaxhighlight>
 
To run these tests from the listener:
 
<langsyntaxhighlight lang="factor">( scratchpad ) "palindrome" test</langsyntaxhighlight>
 
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 586 ⟶ 730:
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].
 
<langsyntaxhighlight lang="fantom">
class TestPalindrome : Test
{
Line 600 ⟶ 744:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
There is no standard or popular facility. Compilers usually do not even check that a function or subroutine is invoked with the correct number of parameters let alone the correct types. Testing that a function returns expected values is entirely a matter for the programmer and whatever tools that may be devised, either directly for the function in question or adapted from some other project where this had been done.
 
 
=={{header|FreeBASIC}}==
{{trans|VBA}}
<syntaxhighlight lang="freebasic">
Sub StrReverse(Byref text As String)
Dim As Integer x, lt = Len(text)
For x = 0 To lt Shr 1 - 1
Swap text[x], text[lt - x - 1]
Next x
End Sub
 
Sub Replace(Byref T As String, Byref I As String, Byref S As String, Byval A As Integer = 1)
Var p = Instr(A, T, I), li = Len(I), ls = Len(S) : If li = ls Then li = 0
Do While p
If li Then T = Left(T, p - 1) & S & Mid(T, p + li) Else Mid(T, p) = S
p = Instr(p + ls, T, I)
Loop
End Sub
 
Function IsPalindrome(Byval txt As String) As Boolean
Dim As String tempTxt = Lcase(txt), copyTxt = Lcase(txt)
Replace(tempTxt, " ", "")
Replace(copyTxt, " ", "")
StrReverse(tempTxt)
If tempTxt = copyTxt Then
Color 10
Return true
Else
Color 12
Return false
End If
End Function
 
'--- Programa Principal ---
Dim As String a(10) => {"abba", "mom", "dennis sinned", "Un roc lamina l animal cornu", _
"palindrome", "ba _ ab", "racecars", "racecar", "wombat", "in girum imus nocte et consumimur igni"}
 
Print !"¨Pal¡ndromos?\n"
For i As Byte = 0 To Ubound(a)-1
Print a(i) & " -> ";
Print IsPalindrome((a(i)))
Color 7
Next i
Sleep
</syntaxhighlight>
{{out}}
<pre>
¿Palíndromos?
 
abba -> true
mom -> true
dennis sinned -> true
Un roc lamina l animal cornu -> true
palindrome -> false
ba _ ab -> true
racecars -> false
racecar -> true
wombat -> false
in girum imus nocte et consumimur igni -> true
</pre>
 
 
=={{header|Go}}==
Using Go's standard command, go test.
<langsyntaxhighlight lang="go">package pal
 
import "testing"
Line 637 ⟶ 845:
}
}
}</langsyntaxhighlight>
Output of go test:
<pre>
Line 648 ⟶ 856:
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.
 
<langsyntaxhighlight lang="haskell">import Test.QuickCheck
 
isPalindrome :: String -> Bool
Line 667 ⟶ 875:
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)))</langsyntaxhighlight>
 
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 677 ⟶ 885:
for failure. There is no standard framework, but the following example shows
how these tests might be handled.
<langsyntaxhighlight lang="unicon">procedure main()
s := "ablewasiereisawelba"
assert{"test1",palindrome(s)}
Line 696 ⟶ 904:
procedure assertFailure(A)
if @A[2] then write(@A[1],": failed")
end</langsyntaxhighlight>
 
Which outputs:
Line 705 ⟶ 913:
->
</pre>
 
=={{header|Insitux}}==
It is possible to mock any built-in or user-defined function, and assert values are truthy. Testing [[Palindrome_detection#Insitux|Insitux's Palindrome detection entry]].
<syntaxhighlight lang="insitux">(var palindrome? (comp (filter letter?) lower-case (= (reverse %))))
 
;Arrange
(var calls [])
(function record f
(fn (var! calls (append f))
(... (unmocked f) args)))
 
(mock comp (record comp)
filter (record filter)
letter? (record letter?)
lower-case (record lower-case)
= (record =)
reverse (record reverse))
 
(var sentence "In girum imus nocte et consumimur igni.")
 
;Act
(var result (palindrome? sentence))
 
(unmock comp filter letter? lower-case = reverse)
 
;Assert
(assert result)
 
(var occurred (freqs calls))
(assert (= (len sentence) (occurred letter?))) ;letter? is called (len sentence) times
(assert (... = 1 (map occurred [filter lower-case reverse =]))) ;other functions are called only once</syntaxhighlight>
 
=={{header|J}}==
Line 710 ⟶ 949:
 
Tests are contained in a test script <tt>c:\mypath\palindrome_test.ijs</tt> with the following contents:
<langsyntaxhighlight lang="j">NB. Contents of palindrome_test.ijs
 
NB. Basic testing
Line 725 ⟶ 964:
test_palinB=: monad define
assert isPalin0 'ab'
)</langsyntaxhighlight>
 
Example Usage:
<langsyntaxhighlight lang="j"> require 'general/unittest'
unittest 'c:\mypath\palindrome_test.ijs'
Test: c:\mypath\palindrome_test.ijs
palinA .................................. OK
palinB .................................. OK</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|5}}<br>
{{libheader|JUnit}}
<langsyntaxhighlight lang="java5">import static ExampleClass.pali; // or from wherever it is defined
import static ExampleClass.rPali; // or from wherever it is defined
import org.junit.*;
Line 784 ⟶ 1,023:
//some code that should throw a WhateverException
}
}</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="java5">public class RunTests{
public static main(String[] args){
org.junit.runner.JUnitCore.runClasses(PalindromeTest.class/*, other classes here if you have more*/);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 799 ⟶ 1,038:
{{works with|Browserify}}
 
<langsyntaxhighlight lang="javascript">const assert = require('assert');
 
describe('palindrome', () => {
Line 822 ⟶ 1,061:
});
})
});</langsyntaxhighlight>
 
Output:
Line 862 ⟶ 1,101:
 
Here is an example of a file with four test case triplets:
<langsyntaxhighlight lang="sh"># Test case 1:
.
1
Line 880 ⟶ 1,119:
def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial
3
6</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="sh">$ jq --run-tests < jq.tests
 
Testing '.' at line number 3
Line 893 ⟶ 1,132:
Testing 'def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end; factorial' at line number 18
3 of 4 tests passed (0 malformed)
</syntaxhighlight>
</lang>
===Testing jq Libraries===
 
Line 901 ⟶ 1,140:
For example, suppose the file library.jq contains the following definitions:
 
<langsyntaxhighlight lang="jq">def factorial: if . <= 0 then 1 else . * ((. - 1) | factorial) end;
 
def palindrome: explode as $in | ($in|reverse) == $in;</langsyntaxhighlight>
 
and that the file test-library.txt contains the two test triplets:
 
<langsyntaxhighlight lang="sh">import "library" as lib; lib::factorial
3
6
Line 913 ⟶ 1,152:
import "library" as lib; lib::palindrome
"salàlas"
true</langsyntaxhighlight>
 
Then the tests can be run by invoking jq in the usual way:
<langsyntaxhighlight lang="sh">jq --run-tests < test-library.txt</langsyntaxhighlight>
 
=={{header|Jsish}}==
Line 924 ⟶ 1,163:
Given the [[Palindrome detection]] solution of
 
<langsyntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 930 ⟶ 1,169:
}
return str === str.split('').reverse().join('');
}</langsyntaxhighlight>
 
''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 947 ⟶ 1,186:
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.
 
<langsyntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 963 ⟶ 1,202:
isPalindrome('CUB') ==> false
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
Giving
Line 988 ⟶ 1,227:
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).
 
<langsyntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,010 ⟶ 1,249:
isPalindrome('CUB') ==> false
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
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,019 ⟶ 1,258:
Which now looks like
 
<langsyntaxhighlight lang="javascript">/* Palindrome detection, in Jsish */
function isPalindrome(str:string, exact:boolean=true) {
if (!exact) {
Line 1,047 ⟶ 1,286:
isPalindrome('A man, a plan, a canal; Panama!', true) ==> false
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
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,053 ⟶ 1,292:
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.
 
<langsyntaxhighlight lang="javascript">/* Interaction testing */
var trial = console.input();
puts(trial.replace(/a/g, 'b'));
Line 1,067 ⟶ 1,306:
bbccbb
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 1,089 ⟶ 1,328:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using Base.Test
include("Palindrome_detection.jl")
 
Line 1,108 ⟶ 1,347:
@test !palindrome("a11")
@test !palindrome("012")
end</langsyntaxhighlight>
 
{{out}}
Line 1,118 ⟶ 1,357:
=={{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:
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun isPalindrome(s: String) = (s == s.reversed())
Line 1,132 ⟶ 1,371:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,143 ⟶ 1,382:
The following example uses the [https://bitbucket.org/bfad/lspec/ LSpec Library]:
 
<langsyntaxhighlight lang="lasso">// Taken from the Lasso entry in Palindrome page
define isPalindrome(text::string) => {
Line 1,179 ⟶ 1,418:
// 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</langsyntaxhighlight>
 
{{out}}
Line 1,188 ⟶ 1,427:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">assert( ispalindrome("ABCBA") )
assert( ispalindrome("ABCDE") )</langsyntaxhighlight>
 
=={{header|Mathematica}}==
<lang Mathematica>myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]]
On[Assert];myFun[1.0]</lang>
 
Output:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">myFun[x_] := Block[{y},y = x^2; Assert[y > 5]; Sin[y]]
On[Assert];myFun[1.0]</syntaxhighlight>
{{out}}
<pre>Assert::asrtf: Assertion y>5 failed.
0.841471</pre>
Line 1,202 ⟶ 1,439:
=={{header|NetRexx}}==
{{libheader|JUnit}}
<langsyntaxhighlight NetRExxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 1,245 ⟶ 1,482:
 
return
</syntaxhighlight>
</lang>
;Output
<pre>
Line 1,256 ⟶ 1,493:
 
=={{header|Nim}}==
Using assertions (Nono output means all tests were correct,; this only works with debug builds!):
<langsyntaxhighlight lang="nim">proc reversereversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
 
proc isPalindrome(s: string): bool =
s == reversereversed(s)
 
when isMainModule:
Line 1,274 ⟶ 1,511:
assert(not isPalindrome("ba_ ab"))
assert(isPalindrome("ba _ ab"))
assert(not isPalindrome("abab"))</langsyntaxhighlight>
 
Using the unittest“unittest” module:
<langsyntaxhighlight lang="nim">import unittest
 
proc reversereversed(s: string): string =
result = newString(s.len)
for i, c in s:
result[s.high - i] = c
 
proc isPalindrome(s: string): bool =
s == reversereversed(s)
 
when isMainModule:
Line 1,302 ⟶ 1,539:
 
test "no palindrome":
check isPalindrome("foo") == false</langsyntaxhighlight>
 
Output:
{{out}}:
<pre>[OK] empty string
 
Line 1,321 ⟶ 1,559:
ocaml unix.cma -I +oUnit oUnit.cma palindrome.cmo palindrome_tests.ml
 
<langsyntaxhighlight lang="ocaml">open OUnit
open Palindrome
 
Line 1,346 ⟶ 1,584:
"test_palindrome_5" >:: test_palindrome_5]
let _ =
run_test_tt_main suite</langsyntaxhighlight>
 
=={{header|Odin}}==
 
<syntaxhighlight lang="odin">// To run execute: odin test Test_a_function.odin -file
package main
 
import "core:testing"
import "core:strings"
 
is_palindrome :: proc(s: string) -> bool {
return s == strings.reverse(s)
}
 
@(test)
test_is_palindrome :: proc(t: ^testing.T) {
palindromes := []string{"", "a", "aa", "aba", "racecar"}
for i in palindromes {
if !is_palindrome(i) {
testing.errorf(t, "is_palindrome returned false on palindrome %s", i)
}
}
 
non_palindromes := []string{"ab", "abaa", "aaba", "abcdba"}
for i in non_palindromes {
if is_palindrome(i) {
testing.errorf(t, "is_palindrome returned true on non-palindrome %s", i)
}
}
}</syntaxhighlight>
 
=={{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 :
<langsyntaxhighlight Oforthlang="oforth">test: [ "abcd" isPalindrome ]
test: ["abba" isPalindrome ]
test: [ "abcba" isPalindrome ]</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,371 ⟶ 1,638:
{{trans|Raku}}
 
<langsyntaxhighlight lang="perl"># ptest.t
use strict;
use warnings;
Line 1,407 ⟶ 1,674:
ok palindrome_r == $expect, 1, "palindrome_r: $note";
ok palindrome_e == $expect, 1, "palindrome_e: $note";
}</langsyntaxhighlight>
 
The program produces TAP output.
Line 1,460 ⟶ 1,727:
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Requires 0.8.2+, which implements the following routines (and a few others) in builtins/unit_tests.e (an autoinclude)
The only golden rule here is to invoke test_summary() after any [block of] tests have been run, everything else is optional.
<lang Phix>function is_palindrome(sequence s)
<!--<syntaxhighlight lang="phix">(phixonline)-->
return s==reverse(s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
end function
<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: #008080;">function</span> <span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">==</span><span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--set_test_verbosity(TEST_QUIET) -- default, no output when third call removed
--set_test_verbosity(TEST_SUMMARY) -- first and last line only [w or w/o ""]
--set_test_verbosity(TEST_SHOW_FAILED) -- first and last two lines only</span>
<span style="color: #7060A8;">set_test_verbosity</span><span style="color: #0000FF;">(</span><span style="color: #004600;">TEST_SHOW_ALL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- as shown in last two cases below
--set_test_abort(TEST_ABORT) -- abort(1) on failure, after showing the summary
--set_test_abort(TEST_QUIET) -- quietly carry on, the default
--set_test_abort(TEST_CRASH) -- abort immmediately on failure (w/o summary)
--set_test_verbosityset_test_pause(TEST_QUIETTEST_PAUSE_FAIL) -- (default,pause noon outputfailure, whenthe third call removed)default
--set_test_verbosityset_test_pause(TEST_SUMMARYTEST_QUIET) -- (first and last line only [w-- ordisable w/opause ""])on failure
--set_test_pause(TEST_PAUSE) -- always pause</span>
--set_test_verbosity(TEST_SHOW_FAILED_ONLY) -- (first and last two lines only)
set_test_verbosity(TEST_SHOW_ALL) -- (as shown below)
<span style="color: #7060A8;">set_test_module</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"palindromes"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- optional, w/o first line is omitted</span>
<span style="color: #7060A8;">test_true</span><span style="color: #0000FF;">(</span><span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abba"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"abba"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">test_true</span><span style="color: #0000FF;">(</span><span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abba"</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- no desc makes success hidden...
-- ...and failure somewhat laconic</span>
<span style="color: #7060A8;">test_false</span><span style="color: #0000FF;">(</span><span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"not abc"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">test_true</span><span style="color: #0000FF;">(</span><span style="color: #000000;">is_palindrome</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"failure"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"failure"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">test_summary</span><span style="color: #0000FF;">()</span>
<!--</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>
Also note that set_test_pause() has no effect under pwa/p2js and the program will always carry on regardless of any failure, <br>
unless set_test_abort() other than TEST_QUIET is in force. You can of course invoke these routines in a platform-dependent <br>
way, for instance pause on the desktop but abort/stop completely in the browser, should that help.
 
Should you invoke a bunch of tests but forget the final test_summary(), then apart from set_test_abort(TEST_CRASH) any
--set_wait_on_summary(-1) -- (pause on failure [default])
failures ''will'' slip by completely unnoticed.
--set_wait_on_summary(0) -- (disable pause on failure)
{{out}}
--set_wait_on_summary(1) -- (always pause)
The following shows example output from various set_test_verbosity() settings, with and without any failures.
 
TEST_QUIET with a failing test (no output or pause if no failing tests)<br>
set_test_module("palindromes") -- (optional, w/o first line is omitted)
TEST_SUMMARY with a failure, same output
<pre>
palindromes:
 
4 tests run, 3 passed, 1 failed, 75% success
test_true(is_palindrome("abba"),"abba")
Press any key to continue...
test_true(is_palindrome("abba")) -- (no desc makes success hidden...)
</pre>
-- (...and failure somewhat laconic)
TEST_SUMMARY with no failure (and without set_test_pause(TEST_PAUSE))<br>
test_false(is_palindrome("abc"),"not abc")
TEST_SHOW_FAILED with no failure, ditto
test_true(is_palindrome("failure"),"failure")
<pre>
palindromes:
 
3 tests run, 3 passed, 0 failed, 100% success
test_summary()</lang>
</pre>
Note the default behaviour, if set_test_verbosity() is not invoked, is no output and carry on as normal when all tests pass.
TEST_SHOW_FAILED with a failure
{{out}}
<pre>
palindromes:
failed: failure
 
4 tests run, 3 passed, 1 failed, 75% success
Press any key to continue...
</pre>
TEST_SHOW_ALL with a failure
<pre>
palindromes:
Line 1,493 ⟶ 1,802:
4 tests run, 3 passed, 1 failed, 75% success
Press any key to continue...
</pre>
TEST_SHOW_ALL with no failure (and without set_test_pause(TEST_PAUSE))
<pre>
palindromes:
passed: abba
passed: not abc
 
3 tests run, 3 passed, 0 failed, 100% success
</pre>
 
Line 1,498 ⟶ 1,815:
The '[http://software-lab.de/doc/refT.html#test test]' function is
built into PicoLisp.
<langsyntaxhighlight PicoLisplang="picolisp">(de palindrome? (S)
(= (setq S (chop S)) (reverse S)) )
 
(test T (palindrome? "racecar"))
(test NIL (palindrome? "ferrari"))</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 1,509 ⟶ 1,826:
It can also be run by using the run_tests predicate.
 
<langsyntaxhighlight Prologlang="prolog">palindrome(Word) :- name(Word,List), reverse(List,List).
 
:- begin_tests(palindrome).
Line 1,516 ⟶ 1,833:
test(invalid_palindrome, [fail]) :- palindrome('this is not a palindrome').
 
:- end_tests(palindrome).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
PureBasic allows for definition of Assert() and other tools & the debugger is integrated into the native editor.
<langsyntaxhighlight PureBasiclang="purebasic">Macro DoubleQuote
; Needed for the Assert-Macro below
" ; " second dlbquote to prevent Rosettas misshighlighting of following code. Remove comment before execution!
Line 1,546 ⟶ 1,863:
text2$="wisconsin"
Assert(IsPalindrome(text1$), "Catching this would be a fail")
Assert(IsPalindrome(text2$), "Catching this is correct")</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="python">def is_palindrome(s):
'''
>>> is_palindrome('')
Line 1,589 ⟶ 1,906:
 
if __name__ == "__main__":
_test()</langsyntaxhighlight>
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,668 ⟶ 1,985:
14 passed and 0 failed.
Test passed.</pre>
 
=={{header|Quackery}}==
 
Quackery does not have a testing specific library well known to the language's community.
 
=={{header|R}}==
Line 1,673 ⟶ 1,994:
 
See also the functions defineTestSuite and runTestSuite.
<langsyntaxhighlight lang="r">checkTrue(palindroc("aba")) # TRUE
checkTrue(!palindroc("ab")) # TRUE
checkException(palindroc()) # TRUE
checkTrue(palindroc("")) # Error. Uh-oh, there's a bug in the function</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,682 ⟶ 2,003:
Racket has a built-in unit testing library. Tests can be specified next to function implementations or in a testing submodule.
 
<langsyntaxhighlight lang="racket">
#lang racket
(module+ test (require rackunit))
Line 1,699 ⟶ 2,020:
(check-true (palindromb "avoova"))
(check-false (palindromb "potato")))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>use Test;
 
sub palin( Str $string) { so $string.lc.comb(/\w/) eq $string.flip.lc.comb(/\w/) }
 
for
my %tests =
'A man, a plan, a canal: Panama.' => True,
'My dog has fleas' => False,
Line 1,713 ⟶ 2,034:
'1 on 1' => False,
'In girum imus nocte et consumimur igni' => True,
'' => True,
{
;
my ($test, $expected-result) = .kv;
 
plan %tests.elems;
 
for %tests.kv -> $test, $expected-result {
is palin($test), $expected-result,
"\"$test\" is {$expected-result??''!!'not '}a palindrome.";
}
}</lang>
 
done-testing;</syntaxhighlight>
Output:
{{out}}
<pre>1..6
ok 1 - "1 on 1" is not a palindrome.
Line 1,735 ⟶ 2,054:
Retro includes a library for creating automated tests. This is used for checking the standard libraries shipped with Retro.
 
<langsyntaxhighlight Retrolang="retro">needs assertion'
needs hash'
 
Line 1,744 ⟶ 2,063:
: t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert= ; assertion
: test ( - ) t0 t1 ;
test</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,751 ⟶ 2,070:
===stress REXX keywords (used as variables)===
{This was originally written in some form of FORTRAN.}
<langsyntaxhighlight lang="rexx">/*REXX Thisprogram stresses various REXX usesfunctions a(BIFs), lotmany ofBIFs REXXare keywordsused as variables. */
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
signal=(interpret=value);value=(interpret<parse);do upper=value to value
do then=value to exit; pull=''; do otherwise= upper to then-,
end;exit=upper*upper*upper*upper-value-upper;say=' ';return=say say say;
value; select=otherwise-value; if.otherwise=with.otherwise+with.select; end
with.=signal;do then=value to exit;pull='';do otherwise=upper to then-,
if.value;select=otherwise-value; if.otherwisethen=with.value; do otherwise+with.select=value to exit-then;end pull=pull,
if.value=valuesay''say;if.then=value end; do otherwise=value to exit-then; pull=pull center(if.otherwise,,
say''saylength(return)); end; say pull; do otherwise=value to thenexit;pull=pull center(ifwith.otherwise,=,
if.otherwise; end; end; exit 0 /*stick a fork in it, we're all done. */</syntaxhighlight>
length(return));end;say pull;do otherwise=value to exit;with.otherwise=,
{{out|output|text=''':'''}}
if.otherwise;end;end</lang>
'''output'''
<pre>
1
Line 1,780 ⟶ 2,098:
===stress test some REXX BIFs===
This stress tests some of the REXX built-in functions (BIFs).
<langsyntaxhighlight lang="rexx">/*REXX program to showshows a secret message. to the terminal by using REXX built─in functions. */
z.=' '; z= 12-25-2002; y= z; w= -y
z.0= translate( right( time('c'), substr(z, 4, z==y)))
z.1= left( substr( format(z, 2, z==y, , z==y.1), 5), z==y)
z.2= copies( right( symbol('z.'20), z==y), left(w, 1))
z.3= translate( right( date('w'), z==y))
z.5= right( form(), z==y)
z.6= x2c( d2x( x2d( c2x( substr( symbol( substr(z, 2)), 2, z==y))) - 1))
z.7= right( symbol('z.' || (z\==z) ), z==y)
z.8= substr( form(), (z==y) + left(w, 1), z==y)
z.9= reverse( left( form(), z==y))
z.10= left( substr( form(), 6), z==y)
z.11= right( datatype(z), z==y)
z.12= substr( symbol(left(z, z=z)), left(w, 1), z==y)
z.13= left( form(), z==y)
 
do z=-31 to 31;z.32=z.32||z.z;end
do z=-31 to 31; z.32= z.32 || z.z; end
say
say z.32
say</lang>
exit 0 /*stick a fork in it, we're all done. */</syntaxhighlight>
'''output'''
{{out|output|text=''':'''}}
<pre>
 
Line 1,809 ⟶ 2,129:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
assert(IsPalindrome("racecar"))
assert(IsPalindrome("alice"))
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 1,819 ⟶ 2,139:
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.
 
<langsyntaxhighlight lang="ruby">def palindrome?(s)
s == s.reverse
end
Line 1,844 ⟶ 2,164:
assert(palindrome?("ab"), "this test case fails on purpose")
end
end</langsyntaxhighlight>
 
<pre>$ ruby palindrome.rb
Line 1,864 ⟶ 2,184:
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]].)
 
<langsyntaxhighlight lang="ruby"># palindrome.rb
def palindrome?(s)
s == s.reverse
Line 1,891 ⟶ 2,211:
palindrome?("ab").must_equal true, "this test case fails on purpose"
end
end</langsyntaxhighlight>
 
<pre>$ ruby19 palindrome.rb
Line 1,907 ⟶ 2,227:
 
Test run options: --seed 40770</pre>
 
=={{header|Rust}}==
Rust supports two ways of writing unit tests out of the box. Most tests are written
as functions with <code>#[test]</code> attribute. When running <code>cargo test</code>
(Cargo is the build and package manager), these functions are executed. The test
functions are usually placed in a separate module and excluded from regular builds;
as the example shows, the whole module with tests has <code>#[cfg(test)]</code>
attribute which has this effect.
 
The other way is using documentation comments. The documentation can contain code
snippets and <code>rustdoc</code> (or <code>cargo</code>) compiles and runs these
code snippets as tests (it is possible to specify the expected outcome, including
the situation that the snippet should fail to compile). Note that the documentation
tests work for libraries only (as for Rust 1.46) and are not run for binary crates.
 
In either case, the tests are supposed to use <code>assert!</code> macro (and its
variants <code>assert_eq!</code> and <code>assert_ne!</code>) to check the expected
outcomes. These macros can be used in regular code as well and always execute. When
an assertion should be checked in debug builds only, <code>debug_assert!</code> and
its variants can be used instead.
 
<syntaxhighlight lang="rust">/// Tests if the given string slice is a palindrome (with the respect to
/// codepoints, not graphemes).
///
/// # Examples
///
/// ```
/// # use playground::palindrome::is_palindrome;
/// assert!(is_palindrome("abba"));
/// assert!(!is_palindrome("baa"));
/// ```
pub fn is_palindrome(s: &str) -> bool {
let half = s.len();
s.chars().take(half).eq(s.chars().rev().take(half))
}
 
#[cfg(test)]
mod tests {
 
use super::is_palindrome;
 
#[test]
fn test_is_palindrome() {
assert!(is_palindrome("abba"));
}
}</syntaxhighlight>
 
While unit tests are written together with the tested code (and thus may employ the
white-box test approach), the code may be accompanied yet with integration tests,
conventionally provided in the <code>tests/</code> folder. Integration tests are
considered external and use the public interface as any other external code.
 
=={{header|Scala}}==
Line 1,914 ⟶ 2,285:
shown here, being similar to Haskell's QuickCheck.
 
<langsyntaxhighlight lang="scala">import org.scalacheck._
import Prop._
import Gen._
Line 1,931 ⟶ 2,302:
forAll { (s: String) => s.take(s.length / 2) == s.drop((s.length + 1) / 2).reverse || !isPalindrome(s) }
}</langsyntaxhighlight>
 
Output:
Line 1,952 ⟶ 2,323:
SRFI 64 is a popular test library.
 
<langsyntaxhighlight lang="scheme">
(import (srfi 64))
(test-begin "palindrome-tests")
Line 1,959 ⟶ 2,330:
(test-equal #t (palindrome? "ingirumimusnocteetconsumimurigni")) ; another of several test functions
(test-end)
</syntaxhighlight>
</lang>
 
The library reports the number of pass/fail tests at the end; the report may be customised.
Line 1,967 ⟶ 2,338:
{{works with|Db2 LUW}}
{{libheader|db2unit}}
<langsyntaxhighlight lang="sql pl">
CREATE OR REPLACE PROCEDURE TEST_MY_TEST()
BEGIN
Line 1,977 ⟶ 2,348:
CALL DB2UNIT.ASSERT_INT_EQUALS('Same value', EXPECTED, ACTUAL);
END @
</langsyntaxhighlight>
Output:
<pre>
Line 2,015 ⟶ 2,386:
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">import Cocoa
import XCTest
 
Line 2,046 ⟶ 2,417:
}
}
}</langsyntaxhighlight>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
templates palindrome
[$...] -> #
when <=$(last..first:-1)> do '$...;' !
end palindrome
 
test 'palindrome filter'
assert 'rotor' -> palindrome <='rotor'> 'rotor is a palindrome'
assert ['rosetta' -> palindrome] <=[]> 'rosetta is not a palindrome'
end 'palindrome filter'
</syntaxhighlight>
 
=={{header|Tcl}}==
Line 2,052 ⟶ 2,436:
 
{{libheader|tcltest}}
<langsyntaxhighlight lang="tcl">package require tcltest 2
source palindrome.tcl; # Assume that this is what loads the implementation of ‘palindrome’
 
Line 2,065 ⟶ 2,449:
} -returnCodes error -result "wrong # args: should be \"palindrome s\""
 
tcltest::cleanupTests</langsyntaxhighlight>
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>
Note that only a small fraction of the features of the testing framework are demonstrated here. In particular, it does not show off management of conditional execution, the application of setup and cleanup code, and how these things are assembled into a whole test suite for a large system.
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="sh">#!/bin/bash
 
is_palindrome() {
Line 2,084 ⟶ 2,468:
fi
}
</syntaxhighlight>
</lang>
 
is_palindrome "A man, a plan, a canal, Panama!"
Line 2,092 ⟶ 2,476:
=={{header|VBA}}==
Using the StrReverse function after deleted spaces
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 2,108 ⟶ 2,492:
IsPalindrome = (tempTxt = StrReverse(tempTxt))
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>abba is a palidrome ? True
Line 2,120 ⟶ 2,504:
wombat is a palidrome ? False
in girum imus nocte et consumimur igni is a palidrome ? True</pre>
 
=={{header|Wren}}==
{{libheader|Wren-test}}
<syntaxhighlight lang="wren">import "./module" for Expect, Suite, ConsoleReporter
 
var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") }
 
var words = ["rotor", "rosetta", "step on no pets", "été", "wren", "🦊😀🦊"]
var expected = [true, false, true, true, false, true]
 
var TestPal = Suite.new("Pal") { |it|
it.suite("'isPal' function:") { |it|
for (i in 0...words.count) {
it.should("return '%(expected[i])' for '%(words[i])' is palindrome") {
Expect.call(isPal.call(words[i])).toEqual(expected[i])
}
}
}
}
 
var reporter = ConsoleReporter.new()
TestPal.run(reporter)
reporter.epilogue()</syntaxhighlight>
 
{{out}}
<pre>
Palindromes:
'isPal' function:
✓ should return 'true' for 'rotor' is palindrome
✓ should return 'false' for 'rosetta' is palindrome
✓ should return 'true' for 'step on no pets' is palindrome
✓ should return 'true' for 'été' is palindrome
✓ should return 'false' for 'wren' is palindrome
✓ should return 'true' for '🦊😀🦊' is palindrome
 
 
==== Tests Summary ====
6 tests, 6 passed, 0 failed, 0 errors, 0 skipped (1 ms)
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn pali(text){
if (text.len()<2) return(False);
text==text.reverse();
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
// spaces make this not a palindrome
tester.testRun(pali.fp("red rum sir is murder"), Void,False,__LINE__);</langsyntaxhighlight>
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,136 ⟶ 2,559:
</pre>
A test file:
<langsyntaxhighlight lang="zkl">tester:=TheVault.Test.UnitTester.UnitTester(__FILE__);
fcn pali(text){
if (text.len()<2) return(False);
Line 2,146 ⟶ 2,569:
 
tester.stats();
returnClass(tester);</langsyntaxhighlight>
<syntaxhighlight lang ="zkl">zkl paliTest.zkl</langsyntaxhighlight>
{{output}}
<pre>
Line 2,162 ⟶ 2,585:
</pre>
If you had a collection of files to test:
<langsyntaxhighlight lang="zkl">zkl Test.testThemAll -- paliTest.zkl</langsyntaxhighlight>
{{output}}
<pre>
55

edits