Modulo:ScribuntoUnit/man: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
m fix tag HTML
m Errore di digitazione
 
(2 versioni intermedie di 2 utenti non mostrate)
Riga 1:
{{Man modulo}}
Questo modulo fornisce le funzionalità di [[unit testing]] per altri moduli [[Wikipedia:Lua|Lua]]. Per testaetestare un modulo si deve creare un'unità di test separata di solito nella voce <code>Modulo:''Nome modulo''/test</code>. Il modulo viene testato usando il modulo ScribuntoUnit che verifica che le operazioni definite nel modulo di test producano i risultati attesi.
 
== Struttura del modulo di test==
Riga 6:
Per preparare un modulo di test (test suite), iniziate con il codice seguente:
 
<sourcesyntaxhighlight lang="lua">
local myModule = require('Module:MyModule') -- the module to be tested
local ScribuntoUnit = require('Module:ScribuntoUnit')
local suite = ScribuntoUnit:new()
</syntaxhighlight>
</source>
 
Potete quindi aggiungere funzioni di test individuali all'oggetto <code>suite</code> object. Ogni funzine che inizia con <code>test</code> è trattata come un test. (Altre funzioni saranno ingorate da ScribuntoUnit, ma possono essere nei test.)
 
<sourcesyntaxhighlight lang="lua">
function suite:testSomeCall()
self:assertEquals('expected value', myModule.someCall(123))
Riga 24:
self:assertEquals('other expected value', myModule.someOtherCall(456))
end
</syntaxhighlight>
</source>
 
I test che scrivete dovrebbero fare [[Asserzione (informatica)|asserzioni]] che ScribuntoUnit controllerà verificare che siano vere. Per esempio, <code>assertEquals</code> controlla che entrambi gli argomenti che gli vengono passati sono uguali. Se ScribuntoUnit trova un'asserzione falsa il test fallirà generando un messaggio di errore. Il messaggio di errore indica qual è l'asserzione fallita (al momento non vengono effettuati altri controlli).
Riga 30:
Il modulo di test deve terminare ritornando l'oggetto <code>suite</code>.
 
<sourcesyntaxhighlight lang="lua">
return suite
</syntaxhighlight>
</source>
 
== Eseguire i test ==
Riga 44:
L'ultimo parametro di tutti i metodi di test è un messaggio che viene mostrato se la validazione fallisce.
 
<sourcesyntaxhighlight lang="lua">
self:assertEquals('expected value', myModule.someCall(123), 'This tests whether the function x does y.')
</syntaxhighlight>
</source>
 
=== assertTrue, assertFalse ===
 
<sourcesyntaxhighlight lang="lua">
self:assertTrue(actual, message)
self:assertFalse(actual, message)
</syntaxhighlight>
</source>
 
Questi controllano se il risultato dell'asserzione è <code>vero</code> o <code>falso</code>. Nel caso di un un controllo di falsità notate che in Lua i valori <code>false</code> e <code>nil</code> sono falsi, mentre tutto il resto viene valutato vero. Per esempio il numero 0 o una lista vuota sono "veri" in Lua.
 
<sourcesyntaxhighlight lang="lua">
self:assertTrue(2 + 2 == 4)
self:assertTrue('foo')
self:assertFalse(2 + 2 == 5)
self:assertFalse(nil)
</syntaxhighlight>
</source>
 
=== assertStringContains ===
 
<sourcesyntaxhighlight lang="lua">
self:assertStringContains(pattern, s, plain, message)
</syntaxhighlight>
</source>
 
Questi test controllano se il <code>pattern</code> viene trovato nella stringa <code>s</code>. Se <code>plain</code> è vero allora il <code>pattern</code> viene interpretato come testo letterale, altrimenti viene interpretato come [[mw:ExtensionEstensione:Scribunto/LuaManuale referencedi manualriferimento al Lua#Ustring patterns|ustring pattern funzioni di ustring]].
 
Se il pattern onnon viene trovato il messaggio di errore indica il valore del <code>pattern</code> e della stringa <code>s</code>; Se la stringa <code>s</code> è più lunga di 70 caratteri viene visualizzata una versione troncata. Questo metodo è utile per testare specifici comportamenti di testi wiki complessi.
 
<sourcesyntaxhighlight lang="lua">
self:assertStringContains("foo", "foobar") -- passespassa
self:assertStringContains("foo", "fobar") -- failsfallisce
self:assertStringContains(".oo", "foobar") -- passespassa: matchescorrisponde a "foo"
self:assertStringContains(".oo", "foobar", true) -- failsfallisce: . isviene interpretedinterpretato ascome aun literalcarattere characterletterale
</syntaxhighlight>
</source>
 
=== assertNotStringContains ===
 
<sourcesyntaxhighlight lang="lua">
self:assertNotStringContains(pattern, s, plain, message)
</syntaxhighlight>
</source>
 
Questa è l'opposto di <code>assertStringContains</code>. Il test fallirà se <code>pattern</code> viene trovato nella stringa <code>s</code>. Se <code>plain</code> è vero allora <code>pattern</code> viene interpretato come stringa letterale, altrimenti viene interpretato come [[mw:ExtensionEstensione:Scribunto/LuaManuale referencedi manualriferimento al Lua#Ustring patterns |ustring pattern funzioni di ustring]].
 
<sourcesyntaxhighlight lang="lua">
self:assertNotStringContains("foo", "foobar") -- failsfallisce
self:assertNotStringContains("foo", "fobar") -- passespassa
self:assertNotStringContains(".oo", "foobar") -- failsfallisce: matchescorrisponde a "foo"
self:assertNotStringContains(".oo", "foobar", true) -- passespassa: . isviene interpretedinterpretato ascome aun literalcarattere characterletterale
</syntaxhighlight>
</source>
 
=== assertEquals ===
 
<sourcesyntaxhighlight lang="lua">
self:assertEquals(expected, actual, message)
</syntaxhighlight>
</source>
 
ThisQuesto testsverifica whetherse theil firstprimo parameterparametro isè equaluguale toal thesecondo second parameterparametro. IfSe bothentrambi parameterssono are numbersnumeri, thevengono valuesconfrontati arecon insteadla comparedfunzione using {{<code|>assertWithinDelta}}</code> withcon delta 1e-8 (0.00000001) sinceessendo numbersi are[[Numero representedin asvirgola mobile| [[floating point]]s witha limitedprecisione precisionlimitata.
 
<sourcesyntaxhighlight lang="lua">
self:assertEquals(4, calculator.add(2, 2))
</syntaxhighlight>
</source>
 
=== assertWithinDelta ===
 
<sourcesyntaxhighlight lang="lua">
self:assertWithinDelta(expected, actual, delta, message)
</syntaxhighlight>
</source>
 
ForPer twodue numbersnumeri, thisil teststest whetherverifica these firsti isvalori withinhanno auna givenprecisa distancedistanza (delta) fromtra the secondloro. ThisQuesto isè usefulutile toper comparenumeri [[Numero in virgola mobile|floating point]] numbers, whichche aresono usedquelli tousati representnell'installazione numbersstd in the standard installation ofdi Lua. (Toper beessere preciseprecisi, itusa usesnumeri [[double-precisionNumero floatingin virgola pointmobile a doppia precisione|double]] numbers).) For examplePer esempio, onnella theversione version ofdi Scribunto installedinstallata onsu theWikipedia English Wikipediainglese, the expressionl'espressione <code>0.3 – 0.2 == 0.1</code> evaluatesviene tovalutata <code>false</code>. ThisQuesto isper becauseil in practice, thefatto expressionche <code>0.3 – 0.2</code> equalsè uguale a <code>0.09999999999999997780…</code> ande theil numbernumero <code>0.1</code> equalsè uguale a <code>0.10000000000000000555…</code>. TheIl piccolo slighterrore errortra betweeni thedue twovuole meansdire thatche Lua doesnon notli considerconsidera them equaluquali. ThereforeQuindi, toil test forper equalityl'uguaglianza betweentra twodue numeri floating point numbers, weè shouldvero acceptall'interno values within adi smalluna distancedistanza (delta) ofpiccola eachtra otherloro, notnon justproprio equalvalori valuesuguali. NoteQuesto thatproblema thisnon probleminfluenza doesi notnumeri affect integersinteri, whichche cansono berappresentati representedusando exactly[[Numero usingin double-precisionvirgola floatingmobile pointa numbersdoppia upprecisione|double]] tofino values ofa 2^53.
 
<sourcesyntaxhighlight lang="lua">
self:assertWithinDelta(0.1, calculator.subtract(0.3, 0.2), 1e-10)
</syntaxhighlight>
</source>
 
=== assertDeepEquals ===
 
<sourcesyntaxhighlight lang="lua">
self:assertDeepEquals(expected, actual, message)
</syntaxhighlight>
</source>
 
Testa quando il primo parametro è uguale al secondo. Se i parametri sono tabelle, vengono confrontati con ricorsione, e i loro [[mw:Estensione:Scribunto/Manuale di riferimento al Lua#Metatabella | __eq metametodi]] sono riconosciuti.
This tests whether the first parameter is equal to the second parameter. If the parameters are tables, they are compared recursively, and their [[mw:Extension:Scribunto/Lua reference manual#Metatables|__eq metamethods]] are respected.
 
<sourcesyntaxhighlight lang="lua">
self:assertDeepEquals(table1, table2)
</syntaxhighlight>
</source>
 
=== assertTemplateEquals ===
 
<sourcesyntaxhighlight lang="lua">
self:assertTemplateEquals(expected, template, args, message)
</syntaxhighlight>
</source>
 
Verifica se il primo parametro è uguale a quello di una chiamata di template. Il secondo parametro è il nome del template, il terzo è una tabella contenente gli argomenti del template.
This tests whether the first parameter equals a template call. The second parameter is the template name, and the third parameter is a table of the template arguments.
 
<sourcesyntaxhighlight lang="lua">
self:assertTemplateEquals(4, 'add', {2, 2}) -- truevero ifse {{add|2|2}} equalsè uguale a 4
</syntaxhighlight>
</source>
 
NoteNotate thatche somealcuni tags writtentag in notazione XML notationnon cannotsi bepossono testedtestare correctlycorrettamente; seevedere thela notenota fordella thefunzione successiva <code>assertResultEquals</code> function below.
 
=== assertResultEquals ===
 
<sourcesyntaxhighlight lang="lua">
self:assertResultEquals(expected, text, message)
</syntaxhighlight>
</source>
 
Questo test verifica se il primo parametro è uguale all'espansione di un testo wiki. Il secondo parametro può essere un qualunque testo wiki.
 
<sourcesyntaxhighlight lang="lua">
self:assertResultEquals(4, '{{#invoke:Calculator|add|2|2}}')
</syntaxhighlight>
</source>
 
Notate che alcuni tag speciali scritti in notazione XML, come per esempio <code><nowiki><pre></nowiki></code>, <code><nowiki><nowiki></nowiki></code>, <code><nowiki><gallery></nowiki></code> e <code><nowiki><ref></nowiki></code> non possono essere confrontati direttamente. Questi tag sono convertiti in [[Aiuto:Strip markers|strip marker]] prima di essere proecessatiprocessati dal Lua. PoichèPoiché gli strip marker sono univoci anche se generati da input identici questi test di ugualianza falliranno. Questo discorso si applica anche alle funzioni <code>assertTemplateEquals</code> e <code>assertSameResult</code>.
 
=== assertSameResult ===
 
<sourcesyntaxhighlight lang="lua">
self:assertSameResult(text1, text2, message)
</syntaxhighlight>
</source>
 
Questo verifica se l'espansione di una data stringa di testo wiki, è uguale all'espansione di un'altra stringa di testo wiki. QuesotQuesto può essere utile per verificare che un modulo si comporti nella stessa maniera di un template che è destinato a rimpiazzare.
 
<sourcesyntaxhighlight lang="lua">
self:assertSameResult('{{add|2|2}}', '{{#invoke:Calculator|add|2|2}}')
</syntaxhighlight>
</source>
 
Notate che alcuni tags scritti in notazione XML non possono essere testati correttamente, vedi la nota per la funzione <code>assertResultEquals</code> più sopra.