diff options
| -rw-r--r-- | tests_integration/DefineHandlerTest.php | 162 | ||||
| -rw-r--r-- | tests_integration/dict_mock_server.php | 185 | ||||
| -rw-r--r-- | tests_integration/run.sh | 51 |
3 files changed, 391 insertions, 7 deletions
diff --git a/tests_integration/DefineHandlerTest.php b/tests_integration/DefineHandlerTest.php new file mode 100644 index 0000000..6dcce49 --- /dev/null +++ b/tests_integration/DefineHandlerTest.php @@ -0,0 +1,162 @@ +<?php +use PHPUnit\Framework\TestCase; + +final class DefineHandlerTest extends ApiTestCase +{ + // ── Authentication ─────────────────────────────────────────────────────── + + public function test_define_requires_authentication(): void + { + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => 'cat', + ]); + + $this->assertEquals(401, $status); + $this->assertArrayHasKey('error', $body); + } + + // ── Disabled dict server ───────────────────────────────────────────────── + + public function test_define_with_disabled_dict_server(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + // When DICT_SERVER is empty, handler returns disabled message + // (This test verifies the early-return path) + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => 'cat', + ]); + + // If dict server is not configured, returns disabled message + // If it is configured (mock), returns definitions + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + // Either disabled message or definitions + $isDisabled = isset($body['result'][0]) && $body['result'][0] === 'Dictionary lookups are disabled.'; + $isDefined = isset($body['result'][0]) && str_contains($body['result'][0], '<strong>'); + $this->assertTrue($isDisabled || $isDefined, 'Expected either disabled message or definitions'); + } + + // ── With mock dict server ──────────────────────────────────────────────── + + public function test_define_returns_definitions_for_known_word(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => 'cat', + ]); + + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + $this->assertNotEmpty($body['result']); + // First result should be the word with <strong> tags + $this->assertEquals('<strong>cat</strong>', $body['result'][0]); + // Followed by definition(s) + $this->assertGreaterThan(1, count($body['result'])); + } + + public function test_define_truncates_word_until_match(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + // "cats" → handler tries "cats" → not found → tries "cat" → found + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => 'cats', + ]); + + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + $this->assertNotEmpty($body['result']); + // Should match "cat" definition + $this->assertEquals('<strong>cats</strong>', $body['result'][0]); + } + + public function test_define_returns_no_results_for_unknown_word(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => 'xyznonexistent', + ]); + + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + $this->assertNotEmpty($body['result']); + // Should return "No results for: <b>xyznonexistent</b>" + $this->assertStringContainsString('No results for:', $body['result'][0]); + $this->assertStringContainsString('xyznonexistent', $body['result'][0]); + } + + public function test_define_strips_html_tags_from_word(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => '<script>cat</script>', + ]); + + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + $this->assertNotEmpty($body['result']); + // Word should be stripped to just "cat" + $this->assertStringNotContainsString('<script>', $body['result'][0]); + } + + public function test_define_handles_soft_hyphens(): void + { + // Login + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'perform-login', + 'user' => 'test', + 'password' => 'test', + ]); + $this->assertEquals(200, $status); + + // "helloworld" contains a soft hyphen () which should be stripped + [$status, $body] = $this->post($this->apiUrl, [ + 'op' => 'define', + 'word' => "hello\u{00AD}world", + ]); + + $this->assertEquals(200, $status); + $this->assertArrayHasKey('result', $body); + $this->assertNotEmpty($body['result']); + } +} diff --git a/tests_integration/dict_mock_server.php b/tests_integration/dict_mock_server.php new file mode 100644 index 0000000..d061266 --- /dev/null +++ b/tests_integration/dict_mock_server.php @@ -0,0 +1,185 @@ +<?php +/** + * Minimal dictd server mock for integration tests. + * + * Implements a subset of the dictd protocol (RFC 2229): + * - Banner on connect + * - DEFINE <db> <word> → returns mock definitions + * - Handles curl's "DEFINE ! db/word" format + * + * Uses pcntl_fork() to handle multiple concurrent clients. + * + * Usage: php dict_mock_server.php <port> + */ + +$port = $argv[1] ?? 0; +if (!$port || !is_numeric($port)) { + fwrite(STDERR, "Usage: php dict_mock_server.php <port>\n"); + exit(1); +} + +$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); +socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); +socket_set_option($socket, SOL_SOCKET, SO_REUSEPORT, 1); +socket_bind($socket, '127.0.0.1', (int)$port); +socket_listen($socket, 16); + +// Mock definitions +$definitions = [ + 'cat' => [ + 'wn:WordNet (r) 3.0 (2006):' => 'A domesticated carnivorous mammal with soft fur.', + 'db:Dictd dictionary:' => 'A small animal that catches mice.', + ], + 'cats' => [ + 'wn:WordNet (r) 3.0 (2006):' => 'Plural of cat.', + ], + 'dog' => [ + 'wn:WordNet (r) 3.0 (2006):' => 'A domesticated carnivorous mammal that barks.', + ], + 'hello' => [ + 'db:Dictd dictionary:' => 'A greeting or salutation.', + ], + 'world' => [ + 'db:Dictd dictionary:' => 'The earth; the globe.', + ], +]; + +/** + * Process a DEFINE command and return the response lines. + */ +function handleDefine(string $command, array $definitions): array +{ + // Handle curl's "DEFINE ! db/word" format + // Also handle standard "DEFINE db word" format + $word = null; + + // Try curl format: DEFINE ! db/word + if (preg_match('/DEFINE\s+\!\s+(\S+\/\S+)/i', $command, $matches)) { + [$_, $dbWord] = $matches; + $parts = explode('/', $dbWord, 2); + if (count($parts) === 2) { + $word = $parts[1]; + } + } + + // Try standard format: DEFINE db word + if ($word === null && preg_match('/DEFINE\s+(\S+)\s+(\S+)/i', $command, $matches)) { + $word = $matches[2]; + } + + if ($word === null) { + return ["110 0 definitions found\n", "250 OK completed\n"]; + } + + // Try exact match first, then strip last char (like the handler does) + $def = null; + $tryWord = $word; + while (strlen($tryWord) > 1 && $def === null) { + if (isset($definitions[$tryWord])) { + $def = $definitions[$tryWord]; + } + $tryWord = mb_substr($tryWord, 0, -1); + } + + if ($def !== null) { + $response = ["110 " . count($def) . " definitions found\n"]; + foreach ($def as $key => $value) { + /* this fakes specific format DefineHandler() expects which may not be completely correct re: dict protocol, i.e. definition (value) starts with space: + + 150 1 definitions retrieved + 151 "cat" mueller7 "Mueller English-Russian Dictionary" + cat + _I [kæt] + 1. _n. + 1) кот; кошка; tom cat кот; pussy cat кошка, кошечка + 2) _зоол. животное семейства кошачьих + */ + + $response[] = "151 $key: $key\n $value\n"; + } + $response[] = "250 Ok\n"; + return $response; + } else { + return ["110 0 definitions found\n", "250 OK completed\n"]; + } +} + +/** + * Process a single client connection. + */ +function handleClient($clientSocket, array $definitions): void +{ + // Send banner + socket_write($clientSocket, "120 mock dictd server ready\n"); + + $buffer = ''; + while (true) { + $data = socket_read($clientSocket, 4096); + if ($data === false || $data === '') { + socket_shutdown($clientSocket, 2); + socket_close($clientSocket); + break; + } + + $buffer .= $data; + + // Process complete commands + while (strpos($buffer, "\n") !== false) { + $newlinePos = strpos($buffer, "\n"); + $line = trim(substr($buffer, 0, $newlinePos)); + $buffer = substr($buffer, $newlinePos + 1); + + if ($line === '') { + continue; + } + + # print("<<< $line\n"); + + // Handle DEFINE command (both curl and standard formats) + if (stripos($line, 'DEFINE') === 0) { + $response = handleDefine($line, $definitions); + foreach ($response as $line_out) { + # print(">>> $line_out"); + socket_write($clientSocket, $line_out); + } + } elseif (stripos($line, 'QUIT') === 0) { + socket_shutdown($clientSocket, 2); // Shutdown send side + socket_close($clientSocket); + return; + } else if (stripos($line, 'CLIENT') === 0) { + socket_write($clientSocket, "250 Ok\n"); + } else { + socket_write($clientSocket, "500 Unknown command\n"); + } + } + } +} + +fwrite(STDERR, "Dict mock server listening on port $port\n"); + +while (true) { + $client = socket_accept($socket); + if ($client === false) { + continue; + } + + // Fork to handle each client concurrently + $pid = pcntl_fork(); + if ($pid === -1) { + // Fork failed, handle in main process + handleClient($client, $definitions); + } elseif ($pid === 0) { + // Child process + socket_close($socket); // Close listener in child + handleClient($client, $definitions); + exit(0); + } else { + // Parent process - reap any finished children periodically + while (($childPid = pcntl_waitpid(-1, $status, WNOHANG)) > 0) { + // Child reaped + } + // Parent continues to accept new connections + } +} + +socket_close($socket); diff --git a/tests_integration/run.sh b/tests_integration/run.sh index 542cc2a..23f5f04 100644 --- a/tests_integration/run.sh +++ b/tests_integration/run.sh @@ -5,9 +5,10 @@ # Orchestrates the full lifecycle: # 1. Start temporary PostgreSQL instance # 2. Create database and run schema migrations -# 3. Start PHP development server -# 4. Run PHPUnit integration tests -# 5. Clean up everything +# 3. Start dict mock server +# 4. Start PHP development server +# 5. Run PHPUnit integration tests +# 6. Clean up everything # # Usage: # ./tests_integration/run.sh [--cleanup-only] [--keep-db] [phpunit args...] @@ -90,6 +91,13 @@ cleanup() { wait "$PHP_SERVER2_PID" 2>/dev/null || true fi + # Stop dict mock server + if [[ -n "${DICT_MOCK_PID:-}" ]] && kill -0 "$DICT_MOCK_PID" 2>/dev/null; then + log "Stopping dict mock server (pid $DICT_MOCK_PID) ..." + kill "$DICT_MOCK_PID" 2>/dev/null || true + wait "$DICT_MOCK_PID" 2>/dev/null || true + fi + # Stop PostgreSQL if [[ -n "${PG_HELPER:-}" ]]; then "$PG_HELPER" stop 2>/dev/null || true @@ -105,6 +113,8 @@ cleanup() { rm -f -- "$PROJECT_ROOT/tests_integration/php_server1.log" rm -f -- "$PROJECT_ROOT/tests_integration/php_server2.log" + rm -f -- "$PROJECT_ROOT/tests_integration/dict_mock.log" + } # ── Main ───────────────────────────────────────────────────────────────────── @@ -167,8 +177,35 @@ export XDEBUG_MODE=coverage $PHP_BIN ./update.php --update-schema=force-yes $PHP_BIN ./update.php --user-add "test:test" -# Step 4: Start PHP development server -log "Step 4/5: Starting PHP development servers, ports: $PHP_PORT1 / $PHP_PORT2..." +# Step 4: Start dict mock server +log "Step 4/6: Starting dict mock server ..." +DICT_MOCK_PORT=9410 +nohup "$PHP_BIN" "$SCRIPT_DIR/dict_mock_server.php" "$DICT_MOCK_PORT" \ + > "$PROJECT_ROOT/tests_integration/dict_mock.log" 2>&1 & +DICT_MOCK_PID=$! +export EPUBE_DICT_SERVER="127.0.0.1:$DICT_MOCK_PORT" + +# Wait for dict mock server to be ready +for i in $(seq 1 20); do + if nc -z 127.0.0.1 "$DICT_MOCK_PORT" 2>/dev/null; then + # Verify dict protocol banner + BANNER=$(echo "" | nc -w 1 127.0.0.1 "$DICT_MOCK_PORT" -vv | head -1) + + if [[ "$BANNER" == "120"* ]]; then + log "Dict mock server is ready on port $DICT_MOCK_PORT." + break + fi + fi + if (( i == 20 )); then + log "Dict mock server did not start in time." + cat "$PROJECT_ROOT/tests_integration/dict_mock.log" >&2 + exit 1 + fi + sleep 0.2 +done + +# Step 5: Start PHP development server +log "Step 5/6: Starting PHP development servers, ports: $PHP_PORT1 / $PHP_PORT2..." # Start PHP server in background, redirect its output nohup "$PHP_BIN" -S "0.0.0.0:$PHP_PORT1" -t "$PROJECT_ROOT" \ @@ -212,8 +249,8 @@ done # curl -vsL "http://localhost:$PHP_PORT1/login.php?op=perform-login&user=test&password=test" # curl -vs "http://localhost:$PHP_PORT1/backend.php?op=healthz" -# Step 5: Run PHPUnit -log "Step 5/5: Running PHPUnit integration tests ..." +# Step 6: Run PHPUnit +log "Step 6/6: Running PHPUnit integration tests ..." # Export env vars for tests export API_URL="http://localhost:$PHP_PORT1/backend.php" |
