Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save samhk222/f5db7f0b58f74d282f3a9d203adc0eb2 to your computer and use it in GitHub Desktop.
Save samhk222/f5db7f0b58f74d282f3a9d203adc0eb2 to your computer and use it in GitHub Desktop.
Teste ordenação do array
<?php
namespace Tests\Unit;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ArrayOrderTest extends TestCase
{
/**
* @param $expected
* @param $data
* @return mixed
* @dataProvider provideDataForArrayTest
*/
public function testValidScenarios($expected, $data)
{
if ($expected) {
return $this->assertTrue($this->isValid($data));
}
return $this->assertFalse($this->isValid($data));
}
/**
* @param array $array
* @return string
*/
public function isValid(array $array)
{
$original = $array;
for ($i = 0; $i <= count($array); $i++) {
// Retira um item do array
unset($array[$i]);
// Como a função de sort transforma o array original, precisamos colocar ele em outra variável para ordenar
$sorted = $array;
asort($sorted);
/**
* Vou retornar true caso o array ordenado seja igual ao array que eu retirei o elemento E
* ele sem os items duplicados seja igual ao array que eu tirei o elemento
*/
if (($sorted === $array) && (array_unique($array) === $array)) {
return true;
}
// Volta o array para o original, para retirar outra chave
$array = $original;
}
return false;
}
/**
* @return array
*/
public function provideDataForArrayTest()
{
return [
[true, [1, 3, 2]],
[true, [10, 1, 2, 3, 4, 5]],
[true, [0, -2, 5, 6]],
[true, [1, 1]],
[true, [1, 2, 5, 3, 5]],
[true, [1, 2, 3, 4, 3, 6]],
[true, [1, 2, 3, 4, 99, 5, 6]],
[true, [123, -17, -5, 1, 2, 3, 12, 43, 45]],
[true, [3, 5, 67, 98, 3]],
[false, [1, 2, 1, 2]],
[false, [1, 3, 2, 1]],
[false, [3, 6, 5, 8, 10, 20, 15]],
[false, [1, 1, 2, 3, 4, 4]],
[false, [1, 4, 10, 4, 2]],
[false, [1, 1, 1, 2, 3]],
[false, [1, 2, 3, 4, 5, 3, 5, 6]],
[false, [40, 50, 60, 10, 20, 30]],
[false, [1, 2, 5, 5, 5]],
[false, [10, 1, 2, 3, 4, 5, 6, 1]],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment