HTMLRestrictionsFieldTest.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * @covers HTMLRestrictionsField
  4. */
  5. class HTMLRestrictionsFieldTest extends PHPUnit\Framework\TestCase {
  6. use MediaWikiCoversValidator;
  7. public function testConstruct() {
  8. $field = new HTMLRestrictionsField( [ 'fieldname' => 'restrictions' ] );
  9. $this->assertNotEmpty( $field->getLabel(), 'has a default label' );
  10. $this->assertNotEmpty( $field->getHelpText(), 'has a default help text' );
  11. $this->assertEquals( MWRestrictions::newDefault(), $field->getDefault(),
  12. 'defaults to the default MWRestrictions object' );
  13. $field = new HTMLRestrictionsField( [
  14. 'fieldname' => 'restrictions',
  15. 'label' => 'foo',
  16. 'help' => 'bar',
  17. 'default' => 'baz',
  18. ] );
  19. $this->assertEquals( 'foo', $field->getLabel(), 'label can be customized' );
  20. $this->assertEquals( 'bar', $field->getHelpText(), 'help text can be customized' );
  21. $this->assertEquals( 'baz', $field->getDefault(), 'default can be customized' );
  22. }
  23. /**
  24. * @dataProvider provideValidate
  25. */
  26. public function testForm( $text, $value ) {
  27. $form = HTMLForm::factory( 'ooui', [
  28. 'restrictions' => [ 'class' => HTMLRestrictionsField::class ],
  29. ] );
  30. $request = new FauxRequest( [ 'wprestrictions' => $text ], true );
  31. $context = new DerivativeContext( RequestContext::getMain() );
  32. $context->setRequest( $request );
  33. $form->setContext( $context );
  34. $form->setTitle( Title::newFromText( 'Main Page' ) )->setSubmitCallback( function () {
  35. return true;
  36. } )->prepareForm();
  37. $status = $form->trySubmit();
  38. if ( $status instanceof StatusValue ) {
  39. $this->assertEquals( $value !== false, $status->isGood() );
  40. } elseif ( $value === false ) {
  41. $this->assertNotSame( true, $status );
  42. } else {
  43. $this->assertSame( true, $status );
  44. }
  45. if ( $value !== false ) {
  46. $restrictions = $form->mFieldData['restrictions'];
  47. $this->assertInstanceOf( MWRestrictions::class, $restrictions );
  48. $this->assertEquals( $value, $restrictions->toArray()['IPAddresses'] );
  49. }
  50. // sanity
  51. $form->getHTML( $status );
  52. }
  53. public function provideValidate() {
  54. return [
  55. // submitted text, value of 'IPAddresses' key or false for validation error
  56. [ null, [ '0.0.0.0/0', '::/0' ] ],
  57. [ '', [] ],
  58. [ "1.2.3.4\n::/0", [ '1.2.3.4', '::/0' ] ],
  59. [ "1.2.3.4\n::/x", false ],
  60. ];
  61. }
  62. }