Skip to content

Commit

Permalink
Add unit tests for Two_Factor_Provider::get_code(). (#522)
Browse files Browse the repository at this point in the history
* Add unit tests for Two_Factor_Provider::get_code().
* Add a test that validates an array of characters results in the correct character output
* Explicitly check the length of the generated codes, and add a test for a string input of valid characters.

---------

Co-authored-by: Ian Dunn <[email protected]>
  • Loading branch information
dd32 and iandunn authored Feb 17, 2023
1 parent f845b1a commit 4bfb2ec
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
2 changes: 1 addition & 1 deletion providers/class-two-factor-provider.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ abstract public function is_available_for_user( $user );
* @param string|array $chars Valid auth code characters.
* @return string
*/
public function get_code( $length = 8, $chars = '1234567890' ) {
public static function get_code( $length = 8, $chars = '1234567890' ) {
$code = '';
if ( is_array( $chars ) ) {
$chars = implode( '', $chars );
Expand Down
37 changes: 37 additions & 0 deletions tests/providers/class-two-factor-provider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
/**
* Test Two Factor Provider
*
* @package Two_Factor
*/

/**
* Class Tests_Two_Factor_Provider
*
* @package Two_Factor
* @group providers
*/
class Tests_Two_Factor_Provider extends WP_UnitTestCase {
/**
* @covers Two_Factor_Provider::get_code
*/
function test_get_code() {
$code = Two_Factor_Provider::get_code( 3, '1' );
$this->assertEquals( '111', $code );

$code = Two_Factor_Provider::get_code( 8, '1' );
$this->assertEquals( '11111111', $code );

$code = Two_Factor_Provider::get_code( 8, 'A' );
$this->assertEquals( 'AAAAAAAA', $code );

$code = Two_Factor_Provider::get_code( 30, array( 'A', 'B', 'C' ) );
$this->assertSame( 1, preg_match( '/^[ABC]{30}$/', $code ) );

$code = Two_Factor_Provider::get_code( 30, 'DEF' );
$this->assertSame( 1, preg_match( '/^[DEF]{30}$/', $code ) );

$code = Two_Factor_Provider::get_code( 8 );
$this->assertEquals( 8, strlen( $code ) );
}
}

0 comments on commit 4bfb2ec

Please sign in to comment.