RingDotNetfor Ring

Testing

Every feature has a test, every sample and application tests itself, and your own programs can do the same.

The test suite#

Shell
sh samples/UsingDotNet/tests/run.sh ring.exe

samples/UsingDotNet/tests/run.sh runs:

  1. every samples/UsingDotNet/tests/test_*.ring (language bridge, collections, LINQ, system, IO, net, services, web, data, entity framework, keyboard, WPF, your own assemblies...),
  2. the package tests (see below),
  3. the console samples,
  4. every tutorial program (the ones with a window test themselves with --selftest, the others just have to run without an error),
  5. every Windows Forms and WPF sample with --selftest,
  6. every application with --selftest,

and prints 0 failed when everything passes. It needs the package bin folder on the PATH; the script adds it for you.

Programs run four at a time, and the windows of the programs that run themselves are invisible and not in the taskbar, so the run takes a few minutes and does not take over your screen. The tutorials about packages run dotnet publish: they need the .NET SDK and, the first time, the internet to get the packages; they run one at a time, because several builds together fail. A tutorial that makes errors on purpose says # errors on purpose on its first lines, and then only an error that was not caught fails it. While you work, run the quick tier, which is only the tests and the console samples and takes about 25 seconds:

Shell
sh samples/UsingDotNet/tests/run.sh ring.exe --quick

Options: --no-packages leaves out the package tests, --packages-only runs only them, --jobs N runs N programs at the same time (--jobs 1 runs them one after the other, which is easier to read when something fails), and --show keeps the windows visible so you can watch them (or set the environment variable RINGDOTNET_SHOW). Run everything before a commit.

On Linux the same script runs the tests, the samples and the package tests; the Windows Forms and WPF programs are the only ones that cannot pass there, because they need the Windows Desktop runtime. The Avalonia samples and applications run there when the computer has a display, and they need the system libraries libICE and libSM (on Debian and Ubuntu: sudo apt install libice6 libsm6). The package tests restore the packages again for the system (a package with a native library has one for each system), so the cache of one system is not used by the other.

Test fileCovers
test_foundation.ring, test_runtime.ring, test_after_error.ringthe bridge: types, overloads, properties, enums, errors, a call after a caught error
test_collections.ring, test_linq.ringtyped collections, LINQ
test_operators.ring, test_span.ring, test_refstruct.ring (also IAsyncEnumerable), test_pointer.ring, test_exceptions.ringoperators and conversions of .NET types, Span parameters and results, ref structs, pointers, exception and attribute classes
test_system.ring, test_io.ring, test_net.ring, test_services.ringthe class library
test_access.ringMicrosoft Access through ODBC (System.Data.Odbc): makes an .accdb file with ADOX, tables, parameters, NULL, Unicode, transactions. Windows with the 64-bit Access Database Engine only; it prints SKIPPED and passes anywhere else
test_desktop.ring, test_keyboard.ringWindows Forms, key handling
test_wpf.ringWPF
test_web.ringASP.NET Core server
test_data*.ringEntity Framework: schema, relations, transactions, migrations, providers, queries, hooks, entities
test_userassembly.ringyour own assemblies: generated classes, interfaces, explicit implementations, extension methods (also of a struct taken by reference and of a delegate type), enum parameters, params arrays, dnIsNull, renamed classes
test_import_folder.ring, test_classindex.ring, test_interface_members.ringloading generated classes from a folder, the class index, interfaces that inherit members
test_native_call.ring, test_handles.ring, test_overload_choice.ring, test_named.ring, test_guard.ringthe native call path, the release of handles, the choice of an overload, named arguments, the managed pointers
test_binary.ring, test_encodings.ringbinary data: every byte value in texts, streams, files, Base64, hashes and byte buffers; legacy code pages (Windows-1256, Shift-JIS, Latin-1) as bytes
test_channels.ringSystem.Threading.Channels: generic types without a Ring class, read with getProp and callMethod, an out value, an optional parameter left out
test_extension_methods.ring, test_more_classes.ring, test_new_forms.ringextension methods and @ names, classes added after the coverage audit, the forms of new
test_using*.ringusing { } and the runtime mode that the namespaces start
test_ready_classes.ring, test_smoke_classes.ringevery ready generic class is a real object; about 200 classes of twenty namespaces are created and given harmless calls (ToString, Equals, the Get, To and Is methods)

Package tests#

samples/UsingDotNet/tests/packages/pkgtest_*.ring are real programs against NuGet packages: 235 tests, one for each package (the ML.NET package has several). Each one asks dnAssert about what the package gives back (HTML, a deserialized list, a determinant, a retried call, rows from a query), so a change of the bridge that breaks a library fails here before it fails in a program. The packages that need a class written in .NET have a small helper project, and the tests that need a native library (LibGit2Sharp, ML.NET, SQLite, SkiaSharp) run on Windows and on Linux.

Writing a package test#

A test is a Ring file in samples/UsingDotNet/tests/packages, next to pkg.ring, and it starts with pkgUse (run one with ring pkgtest_markdig.ring in that folder):

Ring
load "pkg.ring"
pkgUse("markdig",[["Markdig","1.6.0"]],[["Markdig.dll",["Markdig","Markdig.Syntax"]]])
pkgImport("markdig","Markdig.dll","Markdig")

To add a package, copy one of the tests and run it, or run all of them with sh run.sh --packages-only. What pkgUse does:

Helper projects#

A package that needs a class written in .NET uses a small helper project: a validator that derives from AbstractValidator<T>, a mapping profile, request handlers, an interceptor that calls a Ring callback, a class with [MessagePackObject] or [Option] attributes, a job of a scheduler, the rows of an ML.NET model (that helper also references the ML.NET packages for OLS, time series, LightGBM and recommendation). On Linux the MKL library of ML.NET needs the Intel OpenMP runtime (libiomp5, for example apt install libiomp5); without it the tests that use MKL print a NOTE and leave those checks out. packages/helpers/ has PkgHelpers, CastleHelpers, AttributeHelpers, QuartzHelpers and MlHelpers with those classes.

pkgUseProject publishes a helper project (the packages it references come with it) and wraps the DLLs in the order given: a package first, then the helper whose classes derive from it. The cache is made again when a file of the helper project changed.

Ring
pkgUseProject("fluentvalidation","helpers/PkgHelpers",[["FluentValidation.dll",[...]],["PkgHelpers.dll",["PkgHelpers"]]])

The ML.NET tests share their setup in packages/mlcommon.ring: load "mlcommon.ring" and mlUse() restore ML.NET and import its namespaces; mlNew(seed) makes a context, mlColumns([["x","Single"],...]) and mlLoadCsv(oMl,file,columns) read a CSV file, mlColumn(oData,type,name) gives a column as a Ring list, and mlWrite(name,text) writes a file in the cache folder. The AutoML test uses mlUseAuto() and the helper project MlAutoHelpers, in a cache folder of its own: AutoML brings the deep learning packages, about 400 megabytes.

Newer versions#

The newest versions of many packages are audited by tools/dotnettools/auditpackages.ring (see The generator).

What the tests cover#

Each table lists the packages of an area. The second column is the name of the test file (pkgtest_<name>.ring).

HTML, Markdown and templates#

PackageTestWhat it checks
AngleSharpanglesharpan HTML5 parser with the DOM of a browser: CSS selectors, attributes, text, and changing the document
HtmlAgilityPackhtmlagilitypackHTML parsed (also bad HTML), XPath, attributes, text, and changing the document
FizzlerfizzlerCSS selectors over HtmlAgilityPack nodes
HtmlSanitizerhtmlsanitizerunsafe HTML made safe (scripts, event handlers and bad URLs removed), with the lists of allowed tags and attributes
SmartReadersmartreaderthe article of a web page (title, author, text) taken from HTML text
ReverseMarkdownreversemarkdownHTML converted to Markdown
MarkdigmarkdigMarkdown to HTML (a static method, then a pipeline object) and the parsed document
CommonMark.NETcommonmarkthe reference Markdown converter and the CommonMark syntax tree
Scribanscribantemplates over a Ring list and values: loops, conditions, functions and parse errors
FluidfluidLiquid templates: a parser, a template context with values, filters, loops, and the errors of parsing
DotLiquiddotliquidtemplates over a Hash: variables, filters, loops and conditions
Handlebars.Nethandlebarstemplates with values, each, if and blocks; the compiled template is called with a dictionary
StubblestubbleMustache templates: sections, inverted sections, escaping and partials
SmartFormatsmartformatnamed and indexed placeholders, plurals, conditions and lists
ExCSSexcssa CSS parser: the style sheet as objects (rules, selectors, properties)
NUglifynuglifyminified JavaScript, CSS and HTML

Parsers, expressions and scripting#

PackageTestWhat it checks
Esprimaesprimathe syntax tree of JavaScript source (declarations, functions, expressions, modules) and syntax errors
GraphQL-Parsergraphqlparserthe syntax tree of a GraphQL document: operations, variables, fields with arguments, selections, fragments
Gherkingherkinthe parser of feature files: features, scenarios, steps, tags, tables, other languages
Sprachespracheparser combinators: a delegate type with extension methods, called on the object
Pidginpidginparser combinators on classes, with the input type and the result type as generic arguments
Superpowersuperpowerparser combinators over text with generic type arguments and a callback
NCalcncalcexpressions with parameters and functions, and expressions that are wrong
DynamicExpressodynamicexpressoC# expressions evaluated at run time, with variables from Ring
System.Linq.Dynamic.CoredynamiclinqLINQ conditions and orderings written as text
Jintjinta JavaScript engine in the process: values go in, scripts run, functions are called, results come back
Jsonata.Net.NativejsonataJSONata queries over JSON text: sums, filters, paths, functions, errors
CommandLineParsercommandlineparseroptions as a class with attributes (a helper project), the parser result and a Ring callback
Mono.Optionsmonooptionsan option set with Ring callbacks for the values and the arguments that are not options
System.CommandLinesystemcommandlinea root command with options, arguments and sub commands parsed from an array, and the action of a command

Text and language helpers#

PackageTestWhat it checks
Humanizerhumanizerextension methods of strings, numbers and time spans
Unidecode.NETunidecodeUnicode text turned into ASCII (Cyrillic, Greek, Chinese, accents, emoji)
SlugifyslugifyURL slugs from texts, with options and replacements of characters
Pluralize.NETpluralizeEnglish plurals and singulars
Porter2Stemmerporter2English words reduced to their stems
VaderSharp2vadersentiment scores of English text
Figglefiggletext as ASCII art in a font
ConsoleTablesconsoletablesa text table from column names and rows, in several formats
Spectre.Consolespectrewidgets (markup, tables, a panel, a rule) drawn on a test console that keeps the text
Fastenshteinfastenshteinthe Levenshtein distance between texts
FuzzySharpfuzzysharpfuzzy matching: scores, the best match of a list
DiffPlexdiffplexthe differences between two texts, line by line and side by side
DiffMatchPatchdiffmatchpatchcharacter diffs, patches made from two texts and applied, fuzzy matching
Farefarerandom text from a regular expression
UAParseruaparsera user agent text parsed into browser, system and device
MimeMappingmimemappingmedia types of file names and extensions, and the reverse
Text in other scripts and every byteencodingsArabic, Chinese and emoji through JSON, YAML, Markdown and a hash, and all 256 byte values through LZ4 and a ZIP

JSON, serialization and data formats#

PackageTestWhat it checks
Newtonsoft.Jsonnewtonsoftserialize, deserialize with type arguments, and LINQ to JSON (JObject, JArray, SelectToken)
Newtonsoft.Json.BsonbsonBSON bytes written to a memory stream and read back
JsonSchema.Netjsonschemaa JSON Schema from text, instances checked against it, and the results of the evaluation
NJsonSchemanjsonschemaschemas read from text, made from a sample document and used to validate JSON texts
JsonPatch.NetjsonpatchRFC 6902 patches (add, replace, remove, move, copy, test), differences of two documents and JSON pointers
YamlDotNetyamla dictionary serialized, and deserialized with a type argument
TomlyntomlynTOML text to a model (tables, arrays, values) and back
CsvHelpercsvhelpera CSV text read row by row with a header and typed fields, and written back
Sepsepa CSV reader built on spans and ref structs
Sylvan.Data.Csvsylvancsva CSV text as a data reader, quoted fields and Arabic text
MessagePackmessagepacka class with attributes (a helper project) serialized to bytes and back
Google.Protobufprotobufthe well-known messages (Timestamp, Duration, Struct), binary and JSON serialization, ByteString
Apache.Avroavroschemas parsed from JSON text into objects and written back
PeterO.CborcborCBOR objects encoded to bytes and decoded again, with the encodings of the CBOR specification
GeoJSON.Netgeojsongeometry objects that serialize with Newtonsoft.Json: positions, points, line strings, features
SharpKmlsharpkmlKML documents built as objects, written as text and read again

Compression, hashing and identifiers#

PackageTestWhat it checks
SharpCompresssharpcompressZIP archives in memory, with entries, names and sizes
SharpZipLibsharpzipliba ZIP archive in memory, GZip of a text, and Tar
DotNetZipdotnetzipa zip archive made in memory from texts and bytes, saved to a stream, read back, with a password
K4os LZ4lz4LZ4 blocks and frames over byte strings
SnappiersnappierSnappy compression of byte arrays through spans
ZstdSharpzstdsharpZstandard compression and decompression with levels
System.IO.HashingiohashingCRC-32 and xxHash over bytes, with known check values
Crc32.NETcrc32netCRC-32 and CRC-32C checksums as numbers and as a hash algorithm object
SimpleBasesimplebaseBase16, Base32 and Base58 encodings, round trips and known values
Hashidshashidsshort ids from numbers and back, with a salt and a minimum length
Sqidssqidsshort unique ids from numbers and back, with an alphabet and a minimum length
NanoidDotNetnanoidrandom ids with a chosen size and alphabet
Ulidulida struct identifier: parsing, text, time, ordering, 16 bytes
RecyclableMemoryStreamrecyclablepooled memory streams: write, seek, read, every byte value

Security and identity#

PackageTestWhat it checks
BCrypt.Netbcryptpassword hashes with a salt and a cost, and the check of a password
Argon2argon2a password hash in the standard encoded text, and its check
Portable.BouncyCastlebouncycastledigests, HMAC, hex and AES in CBC mode with padding
Otp.NETotpnetthe HOTP and TOTP test vectors
jose-jwtjosejwtsigned tokens with a byte key, decoded again and checked with a wrong key
System.IdentityModel.Tokens.Jwtidentitymodeljwtsigned tokens, validation rules, expired and tampered tokens

Documents, images and calendars#

PackageTestWhat it checks
ClosedXMLclosedxmlan Excel workbook, saved and read again
NPOInpoian xlsx written, a formula calculated, the file read back
MiniExcelminiexcelan xlsx written and read as rows
ExcelDataReaderexceldatareaderan xlsx read row by row
DocumentFormat.OpenXmlopenxmla Word document built as objects, saved and opened again
PdfPigpdfpigtext and page data from a PDF file
QuestPDFquestpdfa PDF made from a description in code, with pieces that are Ring callbacks, read back with PdfPig
SixLabors.ImageSharpimagesharppixels, processing steps in a callback, PNG and JPEG in memory
QRCoderqrcodera QR code as PNG bytes, as a matrix of modules and as SVG
ZXing.Netzxinga QR code encoded, drawn as pixel bytes and decoded again
Ical.Neticalneta calendar with an event and a recurrence, written as iCalendar text and read back
MimeKitmimekitan e-mail message built offline, written as MIME text and parsed back

Dates, units, math and geography#

PackageTestWhat it checks
NodaTimenodatimedates, times, periods, instants and time zones
TimeZoneConvertertimezoneconverterIANA and Windows zone names, daylight saving
Cronoscronoscron expressions and the next time a schedule fires
NCrontabncrontabcron schedules, ranges of occurrences, seconds
ColorHelpercolorhelpercolors converted between RGB, HEX, HSL, HSV and CMYK
UnitsNetunitsnetquantities with units, conversions, operators, parsing
ByteSizebytesizea struct with operators, unit conversions and parsing
Fractionsfractionsexact fractions with operators, reduction and conversion
Math.NET Numericsmathnetspecial functions, statistics, matrices and vectors
MathNet.Spatialspatial3D points and vectors
Combinatoricscombinatoricspermutations, combinations and variations of a list
QuikGraphquikgraphgeneric graphs, a topological order, Dijkstra with a cost callback
NetTopologySuitenettopologysuitegeometries from WKT and coordinates: area, distance, relations, overlay, WKT back
ProjNetprojnetcoordinate transformations between WGS84 and Web Mercator
libphonenumberphonenumbersphone numbers parsed, validated and formatted for many countries
IPNetwork2ipnetworkCIDR networks: parse, contain, subnet, supernet, usable addresses
Semversemversemantic versions: parse, compare, precedence, prerelease and build
Enums.NETenumsnetgeneric helpers for enums and flags
PackageTestWhat it checks
Microsoft.Data.Sqlitesqliteconnections, commands, parameters, readers and transactions: whole numbers, fractions, blobs
Dapper with Sqlitedapperan in-memory database, queries with parameters, rows as dictionaries
Dapper with classesdappertypedQuery<Person> mapping rows to objects of a .NET class, and an object as the parameters
SqlKatasqlkataa query builder compiled for several databases
LiteDBlitedba document database in memory: documents, queries, updates, deletes, indexes
Lucene.Netlucenea full-text index in memory, queries by term and by phrase, scores
Microsoft.Data.Analysisdataanalysisa DataFrame of typed columns, filters, sorting, and a CSV read into a frame

Networking and messaging#

PackageTestWhat it checks
FlurlflurlURLs built and taken apart
RestSharprestsharprequests and addresses built without sending
NetMQnetmqsockets talking through an in-process address
Makaretu.DnsdnsDNS messages in the wire format
prometheus-netprometheuscounters, gauges and histograms written in the Prometheus text format

Containers, mapping and application building blocks#

PackageTestWhat it checks
Microsoft.Extensions.DependencyInjectiondependencyinjectiona service collection and a provider: singletons, transients made by a Ring callback, scopes
Microsoft.Extensions.Configurationconfigurationa configuration built from an in-memory dictionary and a JSON stream (the later source wins), sections, keys with colons
Autofacautofaca container of .NET types, resolved by type
SimpleInjectorsimpleinjectora container with Ring delegates
MediatRmediatrrequests and handlers (a helper project), a mediator built from dependency injection, a request sent and a notification published
AutoMapperautomappera mapping profile (a helper project), objects and lists mapped with type arguments
Mapstermapsterobject mapping with two type arguments
FluentValidationfluentvalidationrules in a validator class (a helper project), validation results
Ardalis.GuardClausesguardclausesargument checks that raise errors with the name and the message
Statelessstatelessa state machine with generic states and triggers
OneOfoneofa value that is one of several types, with Match and Switch callbacks
FluentResultsfluentresultsresult objects instead of exceptions
CSharpFunctionalExtensionsfunctionalResult and Maybe
Microsoft.Extensions.Primitivesprimitivesstring values, segments and tokens
Microsoft.Extensions.FileSystemGlobbingglobbingfile patterns matched against a folder
CommunityToolkit.Mvvmmvvmtoolkitcommands with callbacks, their event, and the messenger
Castle DynamicProxycastlea proxy of an interface answered by a Ring callback (a helper project with the interceptor)

Caching, concurrency and resilience#

PackageTestWhat it checks
Pollypollya resilience pipeline with a retry around a Ring function
System.Threading.RateLimitingratelimitingtoken bucket and fixed window limiters made from options
Quartzquartza scheduler with jobs on other threads (a helper project)
Nito.AsyncExnitoasyncexlocks, a producer and consumer queue, a countdown event, a double ended queue
System.Reactivereactiveobservables, subjects and operators with Ring callbacks
System.Linq.AsynclinqasyncLINQ over asynchronous streams
MoreLINQmorelinqextra LINQ methods (Batch, Pairwise, Shuffle and more)
LazyCachelazycachea cache whose value is made by a Ring callback on a miss
BitFaster.Cachingbitfastera generic LRU cache
Microsoft.Extensions.Caching.Memorymemorycachea cache with options, an out value, and expiry
Microsoft.Extensions.ObjectPoolobjectpoolpools of reusable objects, with a provider and a reset policy

Logging and diagnostics#

PackageTestWhat it checks
Serilogseriloga logger that writes to a file: levels, message templates, properties
NLognloga configuration made in code and a memory target
log4netlog4neta repository configured in code with a memory appender
Ben.Demystifierdemystifierreadable stack traces from an exception of a Ring call

Developer tools and code analysis#

PackageTestWhat it checks
RoslynroslynC# text parsed into a syntax tree, walked, compiled and run in memory
Mono.Cecilcecilthe metadata of an assembly file: modules, types, methods, parameters, attributes
ICSharpCode.DecompilerdecompilerC# source text from an assembly file
LibGit2Sharplibgit2sharpa Git repository made in a folder (a native library): commits, history, branches, tags
CliWrapcliwrapa program run with arguments and its output and exit code read

Testing helpers and test data#

PackageTestWhat it checks
FluentAssertionsfluentassertionsShould() assertions that raise errors when a check fails
ShouldlyshouldlyShouldBe and the like on any object
xunit.assertxunitassertthe Assert class: generic Equal, collections, strings, exceptions
NSubstitutensubstitutea substitute of an interface with return values and received calls
AutoFixtureautofixturetest data for any type
Bogusbogusfake data from a seeded generator

Machine learning (ML.NET)#

PackageTestWhat it checks
ML.NET linear regressionmlnet_regressionan SDCA model with weights, metrics and a prediction engine, trained from rows made in Ring (a helper project has the row classes)
ML.NET more classifiersmlnet_classifierslinear SVM, averaged perceptron, SGD and SDCA for a yes or no; naive Bayes, maximum entropy and one-versus-all for several classes
ML.NET more regression and toolsmlnet_regressorsOLS (native MKL: left out on a Linux computer without libiomp5), online gradient descent, Poisson, tweedie, additive models, LightGBM (native), a train and test split, cross validation, and the importance of each feature
ML.NET time seriesmlnet_timeseriesspike detection (IID and SSA), change point detection, and a forecast of the next values (the SSA parts use the native MKL library and are left out on a Linux computer without libiomp5)
ML.NET recommendationmlnet_recommendationmatrix factorization (native) learns the taste of users from ratings and scores pairs it has not seen
ML.NET data transformsmlnet_transformsmin-max, mean-variance and binning scalers, missing values replaced, rows filtered, columns chosen and dropped, keys, one-hot and hashing, words and word bags
ML.NET logistic regressionmlnet_logistictwo trainers, accuracy, AUC, probabilities and the confusion matrix
ML.NET decision treesmlnet_treesFastTree and FastForest for a number and for a yes or no
ML.NET clustering and PCAmlnet_clusteringk-means with cluster distances and metrics, and principal components
ML.NET saved and loaded modelsmlnet_persistencea trained model saved to a file or a stream and loaded again, also by another context, with the same predictions; a pipeline with a text and a category saved with its transforms; a file that is not a model
ML.NET anomaly detectionmlnet_anomalyRandomizedPca trained on normal rows gives high scores and the anomaly label to rows that are far from them, with the area under the curve
ML.NET rankingmlnet_rankingFastTree and LightGBM rankers over queries of documents, with NDCG and DCG
ML.NET calibratorsmlnet_calibrationPlatt, naive and isotonic calibrators turn the score of a linear SVM or a perceptron into a probability
ML.NET AutoMLmlnet_automlexperiments for a number, a yes or no and several classes, the settings of an experiment, the inferred columns of a CSV file, and the best model used like any other (a restore of hundreds of megabytes)
ML.NET chess end game examplemlnet_chessthe example of samples/UsingDotNet/tests/packages/ChessEndgame run as a user runs it: a split of 70 and 30 percent, many algorithms trained and tested, the models saved, evaluated and used to predict (see the chess end game)
ML.NET with a CSV filemlnet_columnsany number of columns read with column definitions made in Ring, scores read as a column
ML.NET with in-memory rowsmlnet_vectorrowsone row class VectorRow for tables of any width
ML.NET with text columnsmlnet_texta category one-hot encoded, a review featurized into word counts, a text label mapped to classes and back
ML.NET with row classes made at run timemlnet_runtimeclassrow classes defined by Ring with System.Reflection.Emit (numbers, texts, yes/nos), found by the bridge by their names

The bridge itself#

PackageTestWhat it checks
Handle releasehandlechurnloops that make thousands of objects from real packages must give their .NET handles back

dnAssert#

Ring
load "dotnet.ring"

using { "System" }

dnAssert("max",new Math().Max(3,9),9)
dnAssert("abs",new Math().Abs(-5),5)
dnTestSummary()
Output
TESTS: 2 passed, 0 failed

A failing assertion prints FAIL: name expected <9> got <3> and counts a failure. dnTestSummary() returns the number of failures.

Programs that test themselves#

The checks of a window program are kept in a file of their own, so the program stays as short as the lesson that shows it. The program is the usual one (here it is the file counter.ring):

Ring
oForm = uiForm("Click counter",260,130)
...
uiRun(oForm)

and next to it, in the folder selftest, the file with the same name (selftest/counter.ring) holds the checks:

Ring
func selfTest

	oForm.Controls.Item(1).PerformClick()
	dnAssert("one click",oCount.Text,"1 clicks")
Shell
ring counter.ring               # the normal program
ring counter.ring --selftest    # the test: prints SELFTEST OK

With --selftest, uiRun loads that file, shows the form, runs selfTest() once the form is shown, closes the form and prints the result. The form must be in the global variable oForm (WPF: oWindow, with wpfRun). A program without a selftest file runs normally; the functions uiTest(oForm, code) and uiEnd() (wpfTest, wpfEnd) do the same steps by hand for a program that keeps its checks inside. uiMessage() prints instead of showing a dialog in a test, and uiAsk() prints the question and answers yes.

Typing keys in tests#

uiSendKeys(oForm,"12{+}30{ENTER}") types into the focused control of your own form. It posts window messages through the real Windows Forms key processing, so it behaves like a user and can never type into another program (which SendKeys could). Keys: {LEFT} {RIGHT} {UP} {DOWN} {ENTER} {ESC} {BACKSPACE} {TAB} {DELETE}, {+} for a plus sign.

Making the screenshots#

The screenshots in this documentation are made by Ring programs in docs/tools: shoot_all.ring (the samples and the applications) and shoot_tutorials.ring (the tutorial programs). Each one starts a program, waits for its window, captures it with PrintWindow, crops it to the frame that Windows draws, saves a PNG and closes the program. The Windows API is called with ring-cffi, so install it once, then run the tools from the docs/tools folder (Windows only):

ringpm install ring-cffi from ysdragon
cd docs/tools
ring shoot_all.ring forms
ring shoot_tutorials.ring g01c

shoot_all.ring takes the kinds to photograph (forms, wpf, apps; no name means all three) and shoot_tutorials.ring takes shot names (no name means every shot). A tutorial shot can run a few lines of Ring in a temporary copy of the program just before its window is shown, to put it in a later state: they are listed in tutorialshots.ring.

Where to go next#

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