|
15 | 15 | use GraphQL\Type\Definition\FieldDefinition;
|
16 | 16 | use Orchestra\Database\ConsoleServiceProvider;
|
17 | 17 | use Orchestra\Testbench\TestCase as BaseTestCase;
|
| 18 | +use PHPUnit\Framework\ExpectationFailedException; |
18 | 19 | use Symfony\Component\Console\Tester\CommandTester;
|
19 | 20 | use Rebing\GraphQL\Tests\Support\Objects\ExampleType;
|
20 | 21 | use Rebing\GraphQL\Tests\Support\Objects\ExamplesQuery;
|
@@ -170,4 +171,66 @@ protected function runCommand(Command $command, array $arguments = [], array $in
|
170 | 171 |
|
171 | 172 | return $tester;
|
172 | 173 | }
|
| 174 | + |
| 175 | + /** |
| 176 | + * Helper to dispatch an internal GraphQL requests. |
| 177 | + * |
| 178 | + * @param string $query |
| 179 | + * @param array $options |
| 180 | + * @return array Supports the following options: |
| 181 | + * - `expectErrors` (default: false): if no errors are expected but present, let's the test fail |
| 182 | + */ |
| 183 | + protected function graphql(string $query, array $options = []): array |
| 184 | + { |
| 185 | + $expectErrors = $options['expectErrors'] ?? false; |
| 186 | + |
| 187 | + $result = GraphQL::query($query); |
| 188 | + |
| 189 | + $assertMessage = null; |
| 190 | + |
| 191 | + if (! $expectErrors && isset($result['errors'])) { |
| 192 | + $appendErrors = ''; |
| 193 | + if (isset($result['errors'][0]['trace'])) { |
| 194 | + $appendErrors = "\n\n".$this->formatSafeTrace($result['errors'][0]['trace']); |
| 195 | + unset($result['errors'][0]['trace']); |
| 196 | + } |
| 197 | + |
| 198 | + $assertMessage = "Probably unexpected error in GraphQL response:\n" |
| 199 | + .var_export($result, true) |
| 200 | + .$appendErrors; |
| 201 | + } |
| 202 | + |
| 203 | + if ($assertMessage) { |
| 204 | + throw new ExpectationFailedException($assertMessage); |
| 205 | + } |
| 206 | + |
| 207 | + return $result; |
| 208 | + } |
| 209 | + |
| 210 | + /** |
| 211 | + * Converts the trace as generated from \GraphQL\Error\FormattedError::toSafeTrace |
| 212 | + * to a more human-readable string for a failed test. |
| 213 | + * |
| 214 | + * @param array $trace |
| 215 | + * @return string |
| 216 | + */ |
| 217 | + private function formatSafeTrace(array $trace): string |
| 218 | + { |
| 219 | + return implode("\n", |
| 220 | + array_map(function (array $row, int $index): string { |
| 221 | + $line = "#$index "; |
| 222 | + $line .= $row['file'] ?? ''; |
| 223 | + if (isset($row['line'])) { |
| 224 | + $line .= "({$row['line']}) :"; |
| 225 | + } |
| 226 | + if (isset($row['call'])) { |
| 227 | + $line .= ' '.$row['call']; |
| 228 | + } |
| 229 | + if (isset($row['function'])) { |
| 230 | + $line .= ' '.$row['function']; |
| 231 | + } |
| 232 | + |
| 233 | + return $line; |
| 234 | + }, $trace, array_keys($trace))); |
| 235 | + } |
173 | 236 | }
|
0 commit comments