This directory contains comprehensive tests for the OpenAiService class, covering both unit tests and integration tests with real API calls.
Test/
├── Unit/ # Unit tests (mock dependencies)
│ └── Model/Service/OpenAiServiceTest.php
├── Integration/ # Integration tests (real API calls)
│ └── Model/Service/OpenAiServiceIntegrationTest.php
├── Helper/ # Test utilities
│ └── ApiKeyHelper.php
├── Bootstrap.php # Test initialization
└── README.md # This file
-
Composer dependencies installed:
composer install
-
For integration tests: Set OpenAI API key
export OPENAI_API_KEY=sk-proj-your-actual-api-key
Run all unit tests:
vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xmlRun specific test class:
vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xml Test/Unit/Model/Service/OpenAiServiceTest.phpRun specific test method:
vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xml --filter testGetApiKeyFromEnvironmentVariable# Set API key first
export OPENAI_API_KEY=sk-proj-your-actual-api-key
# Run integration tests
vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xml --group=integrationexport OPENAI_API_KEY=sk-proj-your-actual-api-key
vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xmlNEVER:
- Commit API keys to the repository
- Share API keys in conversations or messages
- Hardcode API keys in test files
- Log API keys to console or files
Always:
- Use environment variables to store API keys
- Use
ApiKeyHelper::maskApiKey()when logging - Rotate compromised keys immediately
- Use separate keys for development/testing
- Go to https://platform.openai.com/account/api-keys
- Create a new API key
- Copy it and set it as environment variable
use Genaker\MagentoMcpAi\Test\Helper\ApiKeyHelper;
// Get API key
$apiKey = ApiKeyHelper::getApiKey();
// Check if available
if (ApiKeyHelper::isApiKeyAvailable()) {
// Run integration tests
}
// Mask for logging
$masked = ApiKeyHelper::maskApiKey($apiKey);
echo "Using key: {$masked}\n"; // Output: Using key: sk-p...rkey
// Get status
$status = ApiKeyHelper::getStatus();
// Output: ['is_available' => true, 'is_valid_format' => true, 'masked_key' => 'sk-p...rkey']- ✅
testGetApiKeyFromEnvironmentVariable- API key retrieval from env var - ✅
testGetApiKeyThrowsExceptionWhenNotConfigured- Error handling - ✅
testGetApiDomainReturnsDefault- Default domain - ✅
testGetApiDomainReturnsCustom- Custom domain from config - ✅
testGetApiDomainStripsTrailingSlash- Domain format validation - ✅
testTokenPropertiesSetAndRetrieve- Token tracking - ✅
testConstructorInitializesDependencies- Dependency injection - ✅
testApiEndpointConstantsAreDefined- Endpoint constants - ✅
testGoogleApiEndpointConstantsAreDefined- Google API constants - ✅
testMultipleServiceInstancesAreIndependent- Instance isolation
- ⏳
testChatCompletionWithRealApi- Chat completion endpoint - ⏳
testEmbeddingsWithRealApi- Embeddings endpoint - ✅
testTokenUsageTracking- Token counting - ✅
testApiKeyIsValid- API key validation - ✅
testApiDomainConfiguration- Domain configuration - ⏳
testErrorHandlingForInvalidApiKey- Error scenarios - ⏳
testTimeoutHandling- Timeout handling - ⏳
testRateLimitingHandling- Rate limit handling - ⏳
testConcurrentRequests- Concurrent request handling - ⏳
testResponseCaching- Response caching
Legend: ✅ = Ready, ⏳ = Needs Implementation
$ export OPENAI_API_KEY=sk-proj-...
$ vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xml
PHPUnit 9.5.x by Sebastian Bergmann and contributors.
✓ OpenAI API key found (masked: sk-p...key)
Unit Tests:
testGetApiKeyFromEnvironmentVariable ............................ PASS
testGetApiKeyThrowsExceptionWhenNotConfigured ................... PASS
testGetApiDomainReturnsDefault ................................ PASS
testGetApiDomainReturnsCustom ................................. PASS
testGetApiDomainStripsTrailingSlash ........................... PASS
testTokenPropertiesSetAndRetrieve .............................. PASS
testConstructorInitializesDependencies ......................... PASS
testApiEndpointConstantsAreDefined ............................ PASS
testGoogleApiEndpointConstantsAreDefined ..................... PASS
testMultipleServiceInstancesAreIndependent ................... PASS
Integration Tests:
testTokenUsageTracking ......................................... PASS
testApiKeyIsValid .............................................. PASS
testApiDomainConfiguration .................................... PASS
Time: 0.234s, Memory: 12.5MB
OK (13 passed, 7 incomplete)<?php
declare(strict_types=1);
namespace Genaker\MagentoMcpAi\Test\Unit\Model\Service;
use Genaker\MagentoMcpAi\Model\Service\OpenAiService;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
class MyNewTest extends TestCase
{
private $openAiService;
private $mockDependency;
protected function setUp(): void
{
$this->mockDependency = $this->createMock(SomeDependency::class);
$this->openAiService = new OpenAiService($this->mockDependency);
}
public function testMyNewFeature(): void
{
// Arrange
$expected = 'some value';
// Act
$result = $this->openAiService->myMethod();
// Assert
$this->assertEquals($expected, $result);
}
}<?php
declare(strict_types=1);
namespace Genaker\MagentoMcpAi\Test\Integration\Model\Service;
use Genaker\MagentoMcpAi\Test\Helper\ApiKeyHelper;
use PHPUnit\Framework\TestCase;
class MyNewIntegrationTest extends TestCase
{
/**
* @group integration
* @group openai-api
*/
public function testRealApiCall(): void
{
if (!ApiKeyHelper::isApiKeyAvailable()) {
$this->markTestSkipped('API key not available');
}
$apiKey = ApiKeyHelper::getApiKey();
// Make real API call
}
}# Set the API key
export OPENAI_API_KEY=sk-proj-your-key
# Verify it's set
echo $OPENAI_API_KEY# Ensure autoloader is loaded
composer install
# Regenerate autoloader
composer dump-autoload- Check if API key is valid at https://platform.openai.com/account/api-keys
- Ensure your OpenAI account has sufficient credits
- Check API rate limits
- Review error messages carefully
- Always use mocks in unit tests - Don't call real APIs
- Use environment variables for secrets - Never hardcode keys
- Mask sensitive data in logs - Use ApiKeyHelper
- Test error cases - Invalid keys, timeouts, rate limits
- Keep tests isolated - Each test should be independent
- Use descriptive names - Test names should describe what they test
- Test one thing per test - Single responsibility principle
- Use groups for organization - @group integration, @group openai-api
For continuous integration pipelines:
# .github/workflows/tests.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: shivammathur/setup-php@v2
with:
php-version: '8.1'
- run: composer install
- run: vendor/bin/phpunit -c app/code/Genaker/MagentoMcpAi/phpunit.xml
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}For test-related issues:
- Check the troubleshooting section above
- Review test output for specific error messages
- Consult PHPUnit documentation
- Check OpenAI API status at https://status.openai.com
Last Updated: 2024-02-19
Maintainer: Your Organization