RingDotNetfor Ring

Testing your programs

Tests tell you in seconds whether a change broke something. This lesson shows how to write small testable functions, check them with dnAssert, test that errors are raised, and make a window test itself.

What you will learn#

Why test?#

A test is a small program that checks that another piece of code gives the right answers. You run all the tests after every change: if one fails, you know what broke and when. The tests of this package (samples/UsingDotNet/tests/run.sh) are what makes it possible to change the generator and regenerate thousands of classes with confidence.

Make code testable#

DoBecause
small functions with one jobeach can be tested alone
return results instead of printing or showing thema test can check a returned value
pass data in as parameters instead of reading globalsa test can try many inputs
keep window code thin: the logic is in functionslogic is easy to test, windows are not

The program#

samples/UsingDotNet/tutorials/ch13_testing.ring
# testing your programs - small functions, dnAssert, expected errors, a test summary
#   ring ch13_testing.ring            all tests pass
#   ring ch13_testing.ring --break    one test fails on purpose, to show what a failure looks like
load "dotnet.ring"

using {
	"System"
	"System.Text.RegularExpressions"
}

func main

	testFizzBuzz()
	testWordCount()
	testDates()
	testErrors()
	if find(sysargv,"--break") > 0
		testBrokenOnPurpose()
	ok
	nFailed = dnTestSummary()               # prints "TESTS: n passed, m failed" and returns the number of failures

# ---------------------------------------------------------------- the code that is tested (small, with one job each)

func fizzBuzz nNumber

	if nNumber % 15 = 0
		return "FizzBuzz"
	but nNumber % 3 = 0
		return "Fizz"
	but nNumber % 5 = 0
		return "Buzz"
	ok
	return "" + nNumber

func wordCount cText

	if trim(cText) = ""
		return 0
	ok
	return new Regex("\s+").Split(trim(cText)).Length

func daysUntil nYear, nMonth, nDay, nFromYear, nFromMonth, nFromDay

	oFrom = new DateTime(nFromYear,nFromMonth,nFromDay)
	oTo = new DateTime(nYear,nMonth,nDay)
	return oTo.Subtract(oFrom).Days

func toNumber cText

	aResult = new Int32().TryParse(cText)
	if not aResult[1]
		raise("Not a number: " + cText)
	ok
	return aResult[2]

# ---------------------------------------------------------------- the tests: dnAssert(name, actual, expected)

func testFizzBuzz

	dnAssert("3 is Fizz",fizzBuzz(3),"Fizz")
	dnAssert("10 is Buzz",fizzBuzz(10),"Buzz")
	dnAssert("30 is FizzBuzz",fizzBuzz(30),"FizzBuzz")
	dnAssert("7 is 7",fizzBuzz(7),"7")

func testWordCount

	dnAssert("empty text",wordCount(""),0)
	dnAssert("spaces only",wordCount("    "),0)
	dnAssert("one word",wordCount("Ring"),1)
	dnAssert("many spaces between words",wordCount("  Ring   and  .NET "),3)

func testDates

	dnAssert("a week",daysUntil(2024,1,8,2024,1,1),7)
	dnAssert("over a leap day",daysUntil(2024,3,1,2024,2,28),2)
	dnAssert("the same day",daysUntil(2024,5,5,2024,5,5),0)

# Test that an error is raised: catch it and remember that it happened
func testErrors

	dnAssert("a number",toNumber("42"),42)
	lRaised = False
	try
		toNumber("abc")
	catch
		lRaised = True
		dnAssert("the message says why",cCatchError,"Not a number: abc")
	done
	dnAssert("an error was raised",lRaised,True)

func testBrokenOnPurpose

	dnAssert("2 + 2 is 5 (wrong on purpose)",2 + 2,5)
Output
TESTS: 14 passed, 0 failed

When a test fails#

The program has a switch that breaks one test on purpose:

Shell
ring ch13_testing.ring --break
Output
FAIL: 2 + 2 is 5 (wrong on purpose) expected <5> got <4>
TESTS: 14 passed, 1 failed

A failure prints the name of the test, what was expected and what was got. dnTestSummary() prints the totals and returns the number of failures (use it to set an exit code in a script).

How it works#

dnAssert#

dnAssert("name", actual, expected) compares two values. Texts are compared as text, numbers as numbers (with a small tolerance for decimals). A good name says what should be true: "30 is FizzBuzz", "spaces only", "a week".

What to test#

KindExample in the program
normal casesfizzBuzz(3) is Fizz
the edgesan empty text, spaces only, the same day
surprising inputmany spaces between words
errorsa text that is not a number

Testing an error#

You cannot assert an error directly, so catch it, remember that it happened, and assert on the flag and the message:

Ring
lRaised = False
try
	toNumber("abc")
catch
	lRaised = True
	dnAssert("the message says why",cCatchError,"Not a number: abc")
done
dnAssert("an error was raised",lRaised,True)

Windows that test themselves#

A window program can run its own test: put func selfTest in a file with the name of the program in a selftest folder next to it. When the program is started with --selftest, uiRun loads that file, the window opens, selfTest() runs (which clicks buttons with PerformClick() and checks the labels), closes, and prints SELFTEST OK. The tutorials Your first window, Drawing and animation, Layout and richer controls and A project: a to-do list that remembers all have such a file. uiSendKeys(oForm,"12{+}30{ENTER}") types into the form through the real key processing. See Testing for the details and the samples/UsingDotNet/tests/run.sh script that runs everything.

Run them all#

A single script that runs every test and reports a total is what turns tests from a chore into a habit:

Shell
sh samples/UsingDotNet/tests/run.sh ring.exe      # 0 failed

What you learned#

Exercises#

  1. Write isLeapYear(nYear) and test years 1900, 2000, 2023 and 2024.
  2. Write a function that formats a number of seconds as h:mm:ss and test five values, including 0 and 3600.
  3. Add a test for a function that you wrote in an earlier tutorial.
  4. Break a function on purpose and see which tests fail.

Next#

Giving your program to others

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.