Jump to content

Extension:MWUnit/Extending MWUnit

From mediawiki.org

This page has information about MWUnit's code. It is intended for developers that want to modify it or write code that ties into it. It is not intended for site administrators or end-users.

Defining new assertions

[edit]

MWUnit provides a mechanism to define new assertions. To define a new assertion, an extension must register the MWUnitGetAssertionClasses hook:

public static function onMWUnitGetAssertionClasses( array &$classes ) {
        $classes[] = MyAssertion::class;
}

Any assertion class must implement the MWUnit\Assertion\Assertion interface. This interface has the following methods:

getName()
Returns the name of this assertion as used in the parser function magic word, without the `assert_` prefix.
shouldRegister()
Returns true if and only if this assertion should be registered with the Parser. Allows extensions to define conditional assertions.
getRequiredArgumentCount()
Returns the number of arguments required by the assertion.

These methods define metadata used by the assertion factory to register the assertion class. Additionally, the assert() method should be implemented. This method has variable arguments and is therefore not included in the interface.

The first argument passed to the assert() method is the reference to the error message, shown when the assertion fails. This parameter should be set in the function. The next parameters are the parameters passed to the parser call, with the last argument being the optional user-supplied error message. The function should return true if the assertion succeeded, false if the assertion failed or null when the assertion is deemed invalid/risky (i.e. invalid parameters or an exception occurred).

We will be defining the assertion {{#assert_is_foo: foo | bar}}, that only succeeds when the first argument is foo and the second argument is bar. An example implementation of this looks like this:

<?php

use MWUnit\Assertion\Assertion;

class MyAssertion implements Assertion {
        public static function getName(): string {
                return "is_foo";
        }

        public static function shouldRegister(): bool {
                return true;
        }

        public static function getRequiredArgumentCount(): int {
                return 2;
        }

        public static function assert( &$failure_message, $a, $b, $message = null ) {
                // If $message is set, use that as the failure message
                // The message mustn't be escaped, since it will be escaped by the rendering pipeline
                $failure_message = $message ??
                                wfMessage( "mwunit-assert-failure-is-foo", $a, $b )->plain();

                // Return true if and only if $a is "foo" and $b is "bar"
                return $a === "foo" && $b === "bar";
        }
}