PHPackages                             genericmilk/sakura - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. genericmilk/sakura

ActiveLibrary[Testing &amp; Quality](/categories/testing)

genericmilk/sakura
==================

Automated test generation for Laravel applications using OpenAI, Claude, Gemini, or Ollama

1.0.3(10mo ago)138MITPHPPHP ^8.1CI passing

Since Jun 26Pushed 10mo agoCompare

[ Source](https://github.com/genericmilk/sakura)[ Packagist](https://packagist.org/packages/genericmilk/sakura)[ RSS](/packages/genericmilk-sakura/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (7)Versions (4)Used By (0)

 [![Sakura Logo](sakura.png)](sakura.png)Sakura v1.0.3
=============

[](#sakura-v103)

[![Tests](https://github.com/genericmilk/sakura/workflows/Tests/badge.svg)](https://github.com/genericmilk/sakura/actions)[![Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://packagist.org/packages/genericmilk/sakura)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE.md)

🤖 Sakura is a Laravel package that automatically generates comprehensive tests for your PHP classes and functions using OpenAI's GPT-4o-mini, Anthropic's Claude, Google's Gemini, or local Ollama models.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
    - [Basic Usage](#basic-usage)
    - [Advanced Usage](#advanced-usage)
- [AI Providers](#ai-providers)
    - [OpenAI](#openai)
    - [Claude](#claude)
    - [Gemini](#gemini)
    - [Ollama](#ollama)
    - [Setting up Gemini](#setting-up-gemini)
    - [Setting up Claude](#setting-up-claude)
    - [Setting up Ollama](#setting-up-ollama)
- [How It Works](#how-it-works)
    - [1. Code Analysis](#1-code-analysis)
    - [2. Change Detection](#2-change-detection)
    - [3. Test Generation](#3-test-generation)
    - [4. Test Organization](#4-test-organization)
- [Configuration](#configuration)
    - [AI Provider Settings](#ai-provider-settings)
    - [OpenAI Settings](#openai-settings)
    - [Claude Settings](#claude-settings)
    - [Gemini Settings](#gemini-settings)
    - [Ollama Settings](#ollama-settings)
    - [Analysis Directories](#analysis-directories)
    - [Testing Configuration](#testing-configuration)
- [File Structure](#file-structure)
- [Example Output](#example-output)
- [Generated Test Examples](#generated-test-examples)
    - [Pest Feature Test (Controller)](#pest-feature-test-controller)
    - [PHPUnit Unit Test (Service)](#phpunit-unit-test-service)
- [Provider Comparison](#provider-comparison)
- [Troubleshooting](#troubleshooting)
    - [OpenAI Issues](#openai-issues)
    - [Claude Issues](#claude-issues)
    - [Gemini Issues](#gemini-issues)
    - [Ollama Issues](#ollama-issues)
    - [General Issues](#general-issues)
- [Requirements](#requirements)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)

Features
--------

[](#features)

- **Smart Code Analysis**: Automatically detects and tracks changes in your PHP classes and functions
- **Intelligent Test Generation**: Uses OpenAI, Claude, Gemini, or Ollama to generate comprehensive Feature and Unit tests
- **Framework Detection**: Automatically detects whether your project uses Pest or PHPUnit
- **Change Tracking**: Only generates tests for code that has changed or is new
- **Flexible Configuration**: Highly configurable to match your project structure
- **Progress Tracking**: Beautiful CLI interface with progress bars and detailed feedback
- **Multiple AI Providers**: Support for OpenAI API, Claude API, Gemini API, and local Ollama models

Installation
------------

[](#installation)

1. **Install the package via Composer:**

```
composer require genericmilk/sakura
```

2. **Publish the configuration file:**

```
php artisan vendor:publish --tag=sakura-config
```

3. **Configure your AI provider:**

### For OpenAI:

[](#for-openai)

```
sakura_AI_PROVIDER=openai
OPENAI_API_KEY=your-openai-api-key-here
```

### For Claude:

[](#for-claude)

```
sakura_AI_PROVIDER=claude
ANTHROPIC_API_KEY=your-anthropic-api-key-here
```

### For Gemini:

[](#for-gemini)

```
sakura_AI_PROVIDER=gemini
GOOGLE_AI_API_KEY=your-google-ai-api-key-here
```

### For Ollama:

[](#for-ollama)

```
sakura_AI_PROVIDER=ollama
sakura_OLLAMA_BASE_URL=http://localhost:11434
sakura_OLLAMA_MODEL=codellama
```

4. **Optional: Configure additional settings in your `.env` file:**

```
# AI Provider (openai, claude, gemini, or ollama)
sakura_AI_PROVIDER=openai

# OpenAI Settings
sakura_OPENAI_MODEL=gpt-4o-mini
sakura_MAX_TOKENS=4000
sakura_TEMPERATURE=0.3

# Claude Settings
sakura_CLAUDE_MODEL=claude-3-5-sonnet-20241022
sakura_CLAUDE_MAX_TOKENS=4000
sakura_CLAUDE_TEMPERATURE=0.3

# Gemini Settings
sakura_GEMINI_MODEL=gemini-1.5-pro
sakura_GEMINI_MAX_TOKENS=4000
sakura_GEMINI_TEMPERATURE=0.3
sakura_GEMINI_TIMEOUT=60

# Ollama Settings
sakura_OLLAMA_BASE_URL=http://localhost:11434
sakura_OLLAMA_MODEL=codellama
sakura_OLLAMA_MAX_TOKENS=4000
sakura_OLLAMA_TEMPERATURE=0.3
sakura_OLLAMA_TIMEOUT=120

# Testing Configuration
sakura_TEST_FRAMEWORK=auto
sakura_TEST_DIRECTORY=tests
sakura_GENERATE_FEATURE_TESTS=true
sakura_GENERATE_UNIT_TESTS=true
sakura_MAX_TESTS_PER_CLASS=10
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Generate tests for all changed/new code:

```
php artisan sakura:generate-tests
```

### Advanced Usage

[](#advanced-usage)

**Force regeneration of all tests:**

```
php artisan sakura:generate-tests --force
```

**Generate tests for a specific class:**

```
php artisan sakura:generate-tests --class=UserController
```

**Generate tests for a specific function:**

```
php artisan sakura:generate-tests --function=calculateTotal
```

**Dry run (see what would be generated without creating files):**

```
php artisan sakura:generate-tests --dry-run
```

**Override AI provider for this run:**

```
php artisan sakura:generate-tests --provider=gemini
```

AI Providers
------------

[](#ai-providers)

### OpenAI

[](#openai)

- **Pros**: High-quality test generation, reliable API, fast response times
- **Cons**: Requires API key, costs per request
- **Best for**: Production environments, high-quality test generation
- **Models**: GPT-4o-mini, GPT-4o, GPT-4-turbo

### Claude

[](#claude)

- **Pros**: Excellent code understanding, high-quality output, strong reasoning
- **Cons**: Requires API key, costs per request, slightly slower than OpenAI
- **Best for**: Complex codebases, high-quality test generation, reasoning-heavy tasks
- **Models**: Claude 3.5 Sonnet, Claude 3.5 Haiku, Claude 3 Opus

### Gemini

[](#gemini)

- **Pros**: Fast response times, good code understanding, competitive pricing
- **Cons**: Requires API key, costs per request, newer API
- **Best for**: Fast development cycles, cost-effective test generation
- **Models**: Gemini 1.5 Pro, Gemini 1.5 Flash, Gemini 1.0 Pro

### Ollama

[](#ollama)

- **Pros**: Free, runs locally, no API costs, privacy-focused
- **Cons**: Requires local setup, model quality varies, slower inference
- **Best for**: Development environments, privacy-conscious teams
- **Models**: CodeLlama, Llama2, Mistral, DeepSeek Coder

#### Setting up Gemini

[](#setting-up-gemini)

1. **Get a Google AI API key:**

    - Visit
    - Create an account and generate an API key
2. **Configure sakura:**

```
sakura_AI_PROVIDER=gemini
GOOGLE_AI_API_KEY=your-api-key-here
sakura_GEMINI_MODEL=gemini-1.5-pro
```

3. **Test the configuration:**

```
php artisan sakura:generate-tests --provider=gemini --dry-run
```

#### Setting up Claude

[](#setting-up-claude)

1. **Get an Anthropic API key:**

    - Visit
    - Create an account and generate an API key
2. **Configure sakura:**

```
sakura_AI_PROVIDER=claude
ANTHROPIC_API_KEY=your-api-key-here
sakura_CLAUDE_MODEL=claude-3-5-sonnet-20241022
```

3. **Test the configuration:**

```
php artisan sakura:generate-tests --provider=claude --dry-run
```

#### Setting up Ollama

[](#setting-up-ollama)

1. **Install Ollama:**

```
# macOS/Linux
curl -fsSL https://ollama.ai/install.sh | sh

# Windows
# Download from https://ollama.ai/download
```

2. **Start Ollama:**

```
ollama serve
```

3. **Pull a code model:**

```
ollama pull codellama
# or
ollama pull llama2:13b
# or
ollama pull mistral
```

4. **Configure sakura:**

```
sakura_AI_PROVIDER=ollama
sakura_OLLAMA_MODEL=codellama
```

How It Works
------------

[](#how-it-works)

### 1. Code Analysis

[](#1-code-analysis)

sakura analyzes your codebase and creates a tree of all PHP classes and functions in the configured directories:

- Controllers
- Services
- Actions
- Enums
- Commands
- Models
- Repositories
- Jobs
- Listeners
- Notifications

### 2. Change Detection

[](#2-change-detection)

sakura tracks changes by:

- Computing hashes of class content and individual methods
- Comparing current code with previously saved state
- Detecting new classes and functions
- Identifying modified methods

### 3. Test Generation

[](#3-test-generation)

For each changed/new item, sakura:

- Determines the appropriate test type (Feature vs Unit)
- Detects your testing framework (Pest or PHPUnit)
- Generates comprehensive tests using your chosen AI provider
- Saves tests to the appropriate directory structure

### 4. Test Organization

[](#4-test-organization)

Tests are organized following Laravel conventions:

- **Feature tests**: `tests/Feature/` for controllers and HTTP-related code
- **Unit tests**: `tests/Unit/` for services, actions, and business logic
- **Directory structure**: Mirrors your app directory structure

Configuration
-------------

[](#configuration)

### AI Provider Settings

[](#ai-provider-settings)

```
'provider' => env('sakura_AI_PROVIDER', 'openai'), // openai, claude, gemini, ollama
```

### OpenAI Settings

[](#openai-settings)

```
'openai' => [
    'api_key' => env('OPENAI_API_KEY'),
    'model' => env('sakura_OPENAI_MODEL', 'gpt-4o-mini'),
    'max_tokens' => env('sakura_MAX_TOKENS', 4000),
    'temperature' => env('sakura_TEMPERATURE', 0.3),
],
```

### Claude Settings

[](#claude-settings)

```
'claude' => [
    'api_key' => env('ANTHROPIC_API_KEY'),
    'model' => env('sakura_CLAUDE_MODEL', 'claude-3-5-sonnet-20241022'),
    'max_tokens' => env('sakura_CLAUDE_MAX_TOKENS', 4000),
    'temperature' => env('sakura_CLAUDE_TEMPERATURE', 0.3),
],
```

### Gemini Settings

[](#gemini-settings)

```
'gemini' => [
    'api_key' => env('GOOGLE_AI_API_KEY'),
    'model' => env('sakura_GEMINI_MODEL', 'gemini-1.5-pro'),
    'max_tokens' => env('sakura_GEMINI_MAX_TOKENS', 4000),
    'temperature' => env('sakura_GEMINI_TEMPERATURE', 0.3),
    'timeout' => env('sakura_GEMINI_TIMEOUT', 60),
],
```

### Ollama Settings

[](#ollama-settings)

```
'ollama' => [
    'base_url' => env('sakura_OLLAMA_BASE_URL', 'http://localhost:11434'),
    'model' => env('sakura_OLLAMA_MODEL', 'codellama'),
    'max_tokens' => env('sakura_OLLAMA_MAX_TOKENS', 4000),
    'temperature' => env('sakura_OLLAMA_TEMPERATURE', 0.3),
    'timeout' => env('sakura_OLLAMA_TIMEOUT', 120),
],
```

### Analysis Directories

[](#analysis-directories)

```
'analysis' => [
    'directories' => [
        'app/Http/Controllers',
        'app/Models',
        'app/Console/Commands',
        'app/Services',
        'app/Actions',
        'app/Enums',
        'app/Repositories',
        'app/Jobs',
        'app/Listeners',
        'app/Notifications',
        'app/Providers',
        'app/Http/Middleware',
        'app/Http/Requests',
    ],
    'file_extensions' => ['php'],
    'exclude_patterns' => [
        '*Test.php',
        '*Tests.php',
        'TestCase.php',
    ],
],
```

**Note**: Sakura will only analyze directories that exist in your project. If you see "No changes detected" on a fresh installation, you may need to:

1. Adjust the `directories` array to match your project structure
2. Create some PHP classes in the configured directories
3. Run `php artisan sakura:generate-tests --force` to analyze all existing code

### Testing Configuration

[](#testing-configuration)

```
'testing' => [
    'framework' => env('sakura_TEST_FRAMEWORK', 'auto'), // auto, pest, phpunit
    'test_directory' => env('sakura_TEST_DIRECTORY', 'tests'),
    'generate_feature_tests' => env('sakura_GENERATE_FEATURE_TESTS', true),
    'generate_unit_tests' => env('sakura_GENERATE_UNIT_TESTS', true),
    'max_tests_per_class' => env('sakura_MAX_TESTS_PER_CLASS', 10),
],
```

File Structure
--------------

[](#file-structure)

After installation, sakura creates a `.sakura` directory in your project root:

```
your-project/
├── .sakura/
│   ├── code-tree.json    # Tracks your code structure and hashes
│   └── cache.json        # Cached data for performance
├── tests/
│   ├── Feature/          # Generated feature tests
│   └── Unit/             # Generated unit tests
└── config/
    └── sakura.php         # Configuration file

```

Example Output
--------------

[](#example-output)

When you run `php artisan sakura:generate-tests`, you'll see output like:

```
🤖 sakura - AI-Powered Test Generator

🤖 Using Gemini for test generation

📊 Analyzing codebase...
Found 3 items to process:
📝 Changed Classes:
  - App\Http\Controllers\UserController (app/Http/Controllers/UserController.php)
🆕 New Classes:
  - App\Services\EmailService (app/Services/EmailService.php)
  - App\Actions\CreateUser (app/Actions/CreateUser.php)

Do you want to generate tests for these items? (yes/no) [no]:
> yes

[████████████████████████████████████████] 100%

✅ Generated tests for UserController → tests/Feature/Http/Controllers/UserControllerTest.php
✅ Generated tests for EmailService → tests/Unit/Services/EmailServiceTest.php
✅ Generated tests for CreateUser → tests/Unit/Actions/CreateUserTest.php

📊 Summary: 3 successful, 0 failed
💾 Updating code tree...
✅ Test generation completed!

```

Generated Test Examples
-----------------------

[](#generated-test-examples)

### Pest Feature Test (Controller)

[](#pest-feature-test-controller)

```
