# Package Development

- [Introduction](#introduction)
- [Creating a package](#creating-a-package)
- [Service providers](#service-providers)
    - [What a provider can add](#what-a-provider-can-add)
- [Installing a package](#installing-a-package)
    - [Adding the crate](#adding-the-crate)
    - [Enabling package features](#enabling-package-features)
    - [Registering the provider](#registering-the-provider)
- [Configuration](#configuration)
- [Services](#services)
- [Routes](#routes)
- [Middleware](#middleware)
- [Views](#views)
- [Assets](#assets)
    - [Building assets with Vite](#building-assets-with-vite)
- [Migrations](#migrations)
- [Commands and scheduled tasks](#commands)
- [Errors](#errors)
- [Logging](#logging)
- [Checks at boot](#checks-at-boot)
- [Testing packages](#testing-packages)

<a name="introduction"></a>

## Introduction


패키지는 재사용할 기능으로 Laravel을 확장하는 주된 방법입니다. 결제 프로바이더 클라이언트부터 자체 라우트, 뷰, 데이터베이스 테이블을 갖춘 완전한 관리자 패널까지 만들 수 있습니다.


`reqwest`나 `chrono` 같은 범용 Rust 크레이트는 `Cargo.toml`에 추가하면 어느 애플리케이션에서나 사용할 수 있습니다. Laravel 패키지는 여기서 더 나아가 `laravel-rust`에 의존하는 표준 Rust 라이브러리 크레이트로, [service provider](#service-providers)를 통해 애플리케이션에 통합되어 설정, 서비스, 라우트, 뷰, 에셋, 마이그레이션을 추가합니다.


각 부분을 설명하기 위해 자체 설정, 서비스, 라우트, 미들웨어, 뷰, 스타일시트로 영감을 주는 명언을 제공하는 `example-package`를 만들어 보겠습니다.

<a name="creating-a-package"></a>

## Creating a package


`cargo new --lib`로 라이브러리 크레이트를 만든 뒤 기본 기능을 비활성화하여 `laravel-rust`를 추가합니다.

```shell
cargo add laravel-rust --no-default-features
```


Cargo는 의존성 그래프 전체에서 활성화된 기능을 합치므로 패키지의 기본 기능을 켜 두면 설치하는 모든 애플리케이션에 Inertia와 MiniJinja를 강제합니다. `laravel::inertia`를 사용할 때만 `inertia`를, MiniJinja 엔진을 직접 호출할 때만 `minijinja`를, [migrations](#migrations)를 포함할 때 `database`를 활성화하세요.

```toml
# Cargo.toml
[dependencies]
laravel-rust = { version = "0.1", default-features = false, features = ["database"] }
```

<a name="service-providers"></a>

## Service providers


서비스 프로바이더는 `ServiceProvider`를 구현한 구조체이며 패키지가 등록하는 모든 항목의 진입점입니다.

```rust
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;

pub struct InspireServiceProvider;

impl ServiceProvider for InspireServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        // Register your package's default configuration...
    }

    fn register(&self, app: &mut Registrar) {
        // Register services, routes, views, commands, and more...
    }

    async fn boot(&self, app: &Container) -> laravel::Result<()> {
        // Validate configuration or run startup checks...

        Ok(())
    }
}
```


세 메서드는 모두 선택 사항입니다. Laravel은 다음 순서로 호출합니다.


1. **`config`**는 모든 프로바이더에서 기본 [configuration](#configuration)을 등록합니다. 이후 애플리케이션 설정을 실행하므로 앱 설정이 패키지 기본값을 재정의합니다.
2. **`register`**는 모든 프로바이더에서 서비스, 라우트, 뷰, 명령어와 기타 훅을 바인딩합니다. 이 단계에서 설정은 확정되므로 `app.config()`를 확인하여 등록할 항목을 결정할 수 있습니다.
3. **`boot`**는 요청 처리나 명령어 실행 전에 애플리케이션 시작 시 한 번 실행됩니다. 서비스 확인과 [startup checks](#checks-at-boot)에 사용합니다.


서비스는 처음 사용할 때 지연 생성되므로 `register`에서 직접 확인할 수 없습니다. 서비스가 다른 서비스에 의존하면 서비스 팩토리 안에서 의존성을 확인합니다.

<a name="what-a-provider-can-add"></a>

### What a provider can add


`register` 안에서 `Registrar`는 애플리케이션의 `src/app.rs` 콜백에 대응하는 빌더를 제공합니다.

| 빌더 | 등록 대상 | `src/app.rs`의 대응 항목 |
| --- | --- | --- |
| `routing()` | [Routes](#routes)와 내장 [assets](#assets) | `with_routing` |
| `middleware()` | 전역, `web`, `api` [middleware](#middleware) | `with_middleware` |
| `views()` | [View](#views) 네임스페이스, 엔진, 공유 데이터 | `with_views` |
| `events()` | [Event listeners](/rust/docs/events) | `with_events` |
| `commands()` | [Console commands](#commands) | `with_commands` |
| `schedule()` | [Scheduled tasks](#commands) | `with_schedule` |
| `ticks()` | 서버와 큐 워커에서 반복하는 [Ticks](/rust/docs/tasks#ticks) | `with_ticks` |
| `errors()` | 사용자 지정 [error](#errors) 상태와 렌더러 | `with_errors` |
| `logging()` | 사용자 지정 [`tracing` layers](#logging) | `with_logging` |
| `head()` | 기본 [`<head>` tags](/rust/docs/head) | `with_head` |
| `migrations()` | 패키지 [migrations](#migrations) | `with_migrations` |
| `sessions()`, `cache()`, `mail()`, `queue()`, `features()` | [session store](/rust/docs/session#session-stores-of-your-own)나 [cache store](/rust/docs/cache#custom-drivers) 같은 사용자 지정 드라이버 | `with_services` |


패키지는 [authentication guards](/rust/docs/authentication#registering-a-guard)를 등록할 수 없습니다. 애플리케이션만 `with_auth`를 통해 가드를 등록합니다.

<a name="installing-a-package"></a>

## Installing a package


Laravel 패키지는 `Cargo.toml`에 크레이트 추가와 `src/app.rs`에 서비스 프로바이더 등록이라는 명시적인 두 단계로 설치합니다. 프로바이더를 명시적으로 등록하면 시작 순서가 투명해지고 앱이 불러오는 모든 패키지를 한곳에서 확인할 수 있습니다.

<a name="adding-the-crate"></a>

### Adding the crate


애플리케이션 루트 디렉터리에서 `cargo add`로 패키지를 추가합니다.

```shell
cargo add example-package
```


Cargo는 호환되는 최신 버전을 확인하고 `Cargo.toml`의 `[dependencies]`에 크레이트를 추가합니다.

```toml
[dependencies]
example-package = "0.1.0"
```


애플리케이션과 함께 로컬에서 패키지를 개발한다면 `cargo add --path ../example-package`로 로컬 체크아웃을 직접 가리킬 수 있습니다.

<a name="enabling-package-features"></a>

### Enabling package features


컴파일을 빠르게 하고 바이너리를 작게 유지하기 위해 패키지는 명언을 PDF로 내보내는 `pdf` 같은 선택 기능을 Cargo 기능으로 제공하는 경우가 많습니다. 따라서 앱은 실제 사용하는 기능만 컴파일합니다. 패키지를 추가할 때 선택 기능을 활성화할 수 있습니다.

```shell
cargo add example-package --features pdf
```


또는 `Cargo.toml`에서 직접 활성화합니다.

```toml
[dependencies]
example-package = { version = "0.1.0", features = ["pdf"] }
```


패키지가 의존하는 `laravel-rust` 기능을 수동으로 활성화할 필요는 없습니다. Cargo가 컴파일 중 패키지에 필요한 기능과 애플리케이션 기능을 자동으로 합칩니다.

<a name="registering-the-provider"></a>

### Registering the provider


`Cargo.toml`에 크레이트를 추가하면 해당 타입을 가져올 수 있지만 아직 앱에 연결되지는 않습니다. 패키지의 기본 설정, 서비스, 라우트, 뷰, 미들웨어, 마이그레이션을 활성화하려면 `src/app.rs`에서 `with_providers`로 서비스 프로바이더를 등록합니다.

```rust
use laravel::Application;

Application::configure()
    .with_providers(|providers| {
        providers.add(example_package::InspireServiceProvider);
    })
```


프로바이더는 추가한 순서대로 실행되므로 같은 서비스나 설정을 바인딩하면 나중 프로바이더가 앞선 것을 재정의합니다. `Application::configure()` 체인에서 `with_providers`의 위치와 관계없이 앱 자체의 콜백(`with_config`, `with_services`, `with_routing`, `with_middleware` 등)은 모든 프로바이더 뒤에서 실행되어 앱이 패키지 기본값을 언제나 수정하거나 교체할 수 있습니다.

<a name="configuration"></a>

## Configuration


대부분의 패키지는 API 키, 기능 토글, 기본 동작 같은 설정을 제공해야 합니다. 패키지에서 `Section`을 파생한 공개 [configuration section](/rust/docs/configuration#your-own-config-sections) 구조체를 정의하고 필드에 `#[env(..)]`를 지정하면 앱이 환경 변수로 설정할 수 있습니다.

```rust
use laravel::config::Section;

#[derive(Debug, Clone, Section)]
pub struct InspireConfig {
    #[env("INSPIRE_HEADER", default = true)]
    pub header: bool,
    #[env("INSPIRE_QUOTES", separator = "|")]
    pub quotes: Vec<String>,
}
```


Laravel은 앱의 `app` 크레이트에서 `#[derive(Section)]` 구조체를 자동 발견하지만 패키지는 서비스 프로바이더의 `config` 메서드에서 명시적으로 참여합니다. 패키지의 `ServiceProvider::config` 안에서 `config.discover(env!("CARGO_CRATE_NAME"), env)`를 호출하면 패키지 크레이트의 모든 파생 섹션을 환경에서 불러옵니다.

```rust
use laravel::config::{Config, Env};
use laravel::foundation::ServiceProvider;

impl ServiceProvider for InspireServiceProvider {
    fn config(&self, config: &mut Config, env: &Env) {
        config.discover(env!("CARGO_CRATE_NAME"), env);
    }
}
```


`Section`을 파생하지 않고 Rust에서 설정 섹션을 구성해야 한다면 패키지 프로바이더의 `config` 안에서 `config.set(..)`으로 직접 등록할 수 있습니다.


모든 패키지 프로바이더의 `config`가 앱의 `with_config`보다 먼저 실행되므로 앱은 다른 기본값을 유지하면서 `src/app.rs`에서 개별 필드를 재정의할 수 있습니다. 사용하는 앱이 `section_mut`으로 변경할 수 있도록 섹션 구조체에 `Clone`을 파생하세요.

```rust
// src/app.rs (in the consuming application)
use example_package::InspireConfig;
use laravel::Application;

Application::configure()
    .with_config(|config, _| {
        config.section_mut::<InspireConfig>().header = false;
    })
```

<a name="services"></a>

## Services


패키지의 [services](/rust/docs/container)는 `register` 안에 등록합니다. 다음은 `InspireConfig`로 초기화하는 `Quotes` 싱글턴을 등록합니다.

```rust
use laravel::container::Registrar;

#[derive(Clone)]
pub struct Quotes {
    quotes: Vec<String>,
}

impl Quotes {
    pub fn new(quotes: Vec<String>) -> Self {
        Self { quotes }
    }

    pub fn all(&self) -> &[String] {
        &self.quotes
    }
}

fn register(&self, app: &mut Registrar) {
    app.singleton(async |app| {
        let config = app.config().section::<InspireConfig>();

        Ok(Quotes::new(config.quotes.clone()))
    });
}
```


싱글턴 팩토리는 처음 확인할 때 지연 실행되므로 항상 앱의 최종 설정을 봅니다.


[`#[singleton]` or `#[bind]`](/rust/docs/container#service-functions)로 서비스를 정의하고 `app.discover`를 호출하여 크레이트의 속성 기반 서비스, 명령어 함수, 리스너, 예약 작업을 한 번에 등록할 수도 있습니다.

```rust
use laravel::config::Section;
use laravel::container::singleton;

#[singleton]
async fn quotes(config: Section<InspireConfig>) -> laravel::Result<Quotes> {
    Ok(Quotes::new(config.quotes.clone()))
}

fn register(&self, app: &mut Registrar) {
    app.discover(env!("CARGO_CRATE_NAME"));
}
```


앱은 `Inject<Quotes>`로 서비스를 주입하거나 `with_services`에서 교체할 수 있습니다.

<a name="routes"></a>

## Routes


`app.routing()`으로 `web` 또는 `api` 그룹에 라우트를 등록합니다.

```rust
use laravel::container::{Inject, Registrar};

fn register(&self, app: &mut Registrar) {
    app.routing().web(|route| {
        route.get("/inspire", inspire);
    });
}

/// `GET /inspire`: every quote, one per line.
pub async fn inspire(quotes: Inject<Quotes>) -> String {
    quotes.all().join("\n")
}
```


라우트 핸들러를 `pub`으로 만드세요. [routes are identified by their handlers](/rust/docs/routing#routes-are-identified-by-their-handlers)에서 설명하듯 핸들러로 라우트를 식별하므로 앱은 `route!(example_package::inspire)?` 같은 핸들러 경로로 패키지 라우트에 연결합니다.

<a name="middleware"></a>

## Middleware


패키지는 서비스 프로바이더의 `register`에서 `app.middleware()`로 전역, `web`, `api` [middleware](/rust/docs/middleware)를 추가할 수 있습니다. `register` 실행 시 모든 프로바이더의 `config`와 앱의 `with_config`가 끝난 상태이므로 최종 `InspireConfig`를 확인하여 `header`가 활성화된 경우에만 `AddInspiration`을 연결할 수 있습니다.

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

impl ServiceProvider for InspireServiceProvider {
    fn register(&self, app: &mut Registrar) {
        if app.config().section::<InspireConfig>().header {
            app.middleware().web(|web| {
                web.append(AddInspiration);
            });
        }
    }
}
```


사용하는 앱의 `with_middleware`는 모든 프로바이더 뒤에서 실행되므로 `src/app.rs`에서 `web.remove::<AddInspiration>()`으로 패키지 미들웨어를 제거할 수도 있습니다.

<a name="views"></a>

## Views


배포된 Laravel 앱은 패키지 소스 트리가 없는 단일 바이너리이므로 `laravel::embed!`로 템플릿을 포함하고 네임스페이스에 등록합니다. 경로는 패키지 `Cargo.toml`을 기준으로 확인합니다.

```rust
use laravel::container::Registrar;

fn register(&self, app: &mut Registrar) {
    app.views().namespace("inspire", laravel::embed!("resources/views"));
}
```


네임스페이스 뷰는 `view("inspire::quote", data! { quote })`로 렌더링합니다. 앱은 `resources/views/vendor/inspire/quote.html`에 파일을 두어 패키지 뷰를 재정의할 수 있습니다.


프로덕션의 `.html` 뷰에는 앱이 엔진을 제공하므로 패키지에서 `minijinja` 기능을 활성화할 필요가 없습니다. 패키지 자체 테스트에는 개발 의존성으로 활성화하세요.

```shell
cargo add --dev laravel-rust --no-default-features --features minijinja
```


디버그 빌드에서 Laravel은 패키지 디렉터리의 내장 파일을 직접 읽으므로 재컴파일 없이 템플릿 수정이 반영됩니다. 새 파일 추가에는 여전히 재빌드가 필요합니다.

<a name="assets"></a>

## Assets


스타일시트, 스크립트, 이미지를 `laravel::embed!`로 포함하고 `app.routing().assets(..)`로 등록합니다. Laravel은 `/vendor/<namespace>/<path>`에서 제공합니다.

```rust
use laravel::container::Registrar;

fn register(&self, app: &mut Registrar) {
    app.routing().assets("inspire", laravel::embed!("public"));
}
```


Rust나 템플릿에서 [`vendor_asset`](/rust/docs/urls#package-assets)으로 패키지 에셋을 참조합니다.

```html
<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">
```


Laravel은 캐시 무효화를 위해 콘텐츠 해시 쿼리 문자열(`/vendor/inspire/inspire.css?id=34b6aba9…`)을 추가합니다. 앱은 `public/vendor/inspire/`에 대체 파일을 두어 에셋을 재정의할 수 있습니다.

<a name="building-assets-with-vite"></a>

### Building assets with Vite


패키지가 Vite로 JavaScript나 CSS를 컴파일한다면 게시 전에 에셋을 빌드하고, 게시하는 크레이트에 빌드 디렉터리를 포함한 뒤 `laravel::embed!`로 넣으세요. 그러면 사용하는 앱에서 Node나 Vite가 필요하지 않습니다.


진입점이 하나라면 다음 Vite 8 설정은 고정된 파일명(`dist/app.js`, `dist/style.css`)으로 출력합니다.

```js
import { defineConfig } from 'vite';

export default defineConfig({
    base: '/vendor/dashboard/',
    publicDir: false,
    build: {
        outDir: 'dist',
        cssCodeSplit: false,
        rolldownOptions: {
            input: 'resources/js/app.js',
            output: {
                entryFileNames: 'app.js',
                assetFileNames: '[name][extname]',
                codeSplitting: false,
            },
        },
    },
});
```


JavaScript 진입점에서 CSS를 가져오고(`import '../css/app.css'`), 상대 폰트·이미지 URL이 올바르게 확인되도록 `base`를 `/vendor/<namespace>/`로 설정합니다. 빌드 디렉터리를 등록하고 뷰에서 에셋을 연결합니다.

```rust
fn register(&self, app: &mut Registrar) {
    app.routing().assets("dashboard", laravel::embed!("dist"));
}
```

```html
<link rel="stylesheet" href="{{ vendor_asset("dashboard", "style.css") }}">
<script type="module" src="{{ vendor_asset("dashboard", "app.js") }}"></script>
```

<a name="including-the-build-in-the-published-crate"></a>

#### Including the build in the published crate


`embed!`는 앱이 패키지를 컴파일할 때 빌드 파일을 읽으므로 `.gitignore`에서 제외하더라도 `Cargo.toml`에는 `dist/**`를 명시적으로 포함해야 합니다.

```toml
[package]
include = ["src/**", "resources/views/**", "dist/**", "Cargo.toml", "README.md", "LICENSE"]
```


`cargo publish` 전에 `npx vite build`로 프런트엔드 번들을 빌드하고 `cargo package --list`로 공개할 `.crate` 아카이브의 모든 파일을 출력합니다. `dist/app.js`, `dist/style.css`, 뷰가 포함되고 `node_modules/`는 없는지 확인하세요.

```shell
npx vite build
cargo package --list
```

<a name="migrations"></a>

## Migrations


데이터베이스 테이블을 사용하는 패키지는 [migrations](/rust/docs/migrations)를 포함하고 `app.migrations()`로 등록할 수 있습니다. 앱에서 `migrate`를 실행하면 패키지와 앱의 마이그레이션이 파일명 순서대로 함께 실행됩니다.

```rust
use laravel::container::Registrar;

fn register(&self, app: &mut Registrar) {
    app.migrations().add(laravel::db::migrations!("database/migrations"));
}
```


`laravel::db::migrations!`는 컴파일 시 `database/migrations`를 검색하므로 디렉터리 감시를 지시하지 않으면 Cargo가 새 마이그레이션 파일을 자동 감지하지 않습니다. 패키지 크레이트 루트에 `build.rs`를 추가하여 파일 추가, 수정, 이름 변경 시 재컴파일하게 합니다.

```rust
// build.rs
fn main() {
    println!("cargo::rerun-if-changed=database/migrations");
}
```

<a name="commands"></a>

## Commands and scheduled tasks


패키지는 자체 [console commands](/rust/docs/console#writing-commands)를 등록하여 서비스 프로바이더 설치 즉시 앱에 CLI 명령어를 제공할 수 있습니다. `#[command]`로 명령어 함수를 정의하고 필요한 서비스는 `Inject<T>`로 주입합니다.

```rust
use laravel::console::{Console, command};
use laravel::container::Inject;

/// List every inspiring quote.
#[command("inspire:list")]
pub async fn list_quotes(console: &mut Console, quotes: Inject<Quotes>) {
    for quote in quotes.all() {
        console.line(quote);
    }
}
```


`#[command]` 함수를 등록하려면 서비스 프로바이더의 `register`에서 `app.discover(env!("CARGO_CRATE_NAME"))`를 호출합니다. 또는 `app.commands().add::<ListQuotes>()`로 [command structs](/rust/docs/console#command-structs)를 명시적으로 등록합니다. 앱이 같은 이름의 명령어를 정의하면 앱 명령어가 패키지 명령어를 재정의합니다.


반복하는 백그라운드 처리가 필요하면 서비스 프로바이더의 `register`에서 `app.schedule()`로 [scheduled tasks](/rust/docs/scheduling)를 등록할 수도 있습니다.

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;

impl ServiceProvider for BillingServiceProvider {
    fn register(&self, app: &mut Registrar) {
        app.schedule()
            .command("billing:sync-invoices")
            .daily_at("08:00");
    }
}
```


패키지의 예약 작업은 사용하는 앱이 스케줄러를 실행할 때 자동 실행됩니다.

<a name="errors"></a>

## Errors


[`#[derive(Status)]`](/rust/docs/errors#errors-with-their-own-status)로 패키지 도메인 오류에 HTTP 상태 코드를 지정하면 사용하는 앱이 각 오류를 수동 매핑할 필요가 없습니다.

```rust
use laravel::errors::Status;

#[derive(Debug, thiserror::Error, Status)]
#[error("The card was declined.")]
#[status(402)]
pub struct CardDeclined;
```


추가 오류 처리는 서비스 프로바이더의 `register` 안에서 `app.errors()`를 사용합니다. 앱의 `with_errors`와 같은 `Errors` 빌더를 제공합니다. 예를 들어 결제 패키지는 예상되는 거절을 로깅하지 않고, 플래시된 이전 입력에서 민감한 결제 필드를 제외하며, API 요청에는 구조화된 JSON을 렌더링할 수 있습니다.

```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
use laravel::prelude::*;
use serde_json::json;

impl ServiceProvider for BillingServiceProvider {
    fn register(&self, app: &mut Registrar) {
        let errors = app.errors();

        errors.dont_report::<CardDeclined>();
        errors.dont_flash(["card.number", "card.cvc"]);

        errors.render(|error: &CardDeclined, request, status| {
            if !request.wants_json() {
                return None;
            }

            let body = json!({
                "error": "card_declined",
                "message": error.to_string(),
            });

            Some((status, Json(body)).into_response())
        });
    }
}
```


앱의 `with_errors`는 모든 프로바이더 뒤에서 실행되므로 같은 오류 타입에 대한 앱의 상태 매핑과 렌더러가 항상 패키지 기본값보다 우선합니다.

<a name="logging"></a>

## Logging


패키지는 `app.logging()`으로 오류 추적기나 텔레메트리 내보내기 같은 사용자 지정 `tracing` 계층을 연결할 수 있습니다.

```rust
use laravel::container::Registrar;

fn register(&self, app: &mut Registrar) {
    if app.config().section::<TelemetryConfig>().enabled {
        app.logging().layer(telemetry_layer());
    }
}
```


사용자 지정 `tracing` 계층을 만들고 필터링하는 방법은 로깅 가이드의 [sending logs elsewhere](/rust/docs/logging#sending-logs-elsewhere)를 참고하세요.

<a name="checks-at-boot"></a>

## Checks at boot


`boot`에서 오류를 반환하면 앱의 시작이 중단되어 첫 요청 시점이 아닌 배포 시점에 잘못된 설정을 발견할 수 있습니다.

```rust
use laravel::container::Container;
use laravel::http::HeaderValue;

async fn boot(&self, app: &Container) -> laravel::Result<()> {
    if !app.config().section::<InspireConfig>().header {
        return Ok(());
    }

    let quotes = app.resolve::<Quotes>().await?;

    if let Some(quote) = quotes
        .all()
        .iter()
        .find(|quote| HeaderValue::from_str(quote).is_err())
    {
        return Err(laravel::abort_with(
            500,
            format!("The quote `{quote}` can't be sent in a header."),
        ));
    }

    Ok(())
}
```


시작 오류에는 프로바이더 이름이 포함되어 개발자가 실패한 패키지를 바로 식별할 수 있습니다. `boot`는 이런 시작 검사에만 사용하고 등록은 `register`, 서비스 초기화는 서비스 팩토리에서 처리하세요.

<a name="testing-packages"></a>

## Testing packages


패키지 통합 테스트는 크레이트 루트의 `tests/` 디렉터리(예: `tests/package.rs`)에 둡니다. Cargo는 `tests/`의 각 파일을 별도 크레이트로 컴파일하므로 실제 사용하는 앱처럼 공개 API를 통해 패키지를 테스트합니다.


테스트에 `.html` 렌더링용 `minijinja`처럼 패키지의 `[dependencies]`에서 활성화하지 않은 기능이 필요하면 `Cargo.toml`의 `[dev-dependencies]`에 추가하세요. 패키지를 설치하는 앱에는 포함되지 않습니다.

```toml
# Cargo.toml
[dev-dependencies]
laravel-rust = { version = "0.1", default-features = false, features = ["minijinja"] }
```


패키지에는 앱과 달리 `src/app.rs`나 `src/testing.rs`가 없습니다. 대신 `tests/package.rs`에 `configure`와 `create` 헬퍼를 정의하여 `for_testing(env!("CARGO_MANIFEST_DIR"))`로 최소 테스트 앱을 만들고 프로바이더를 등록한 뒤 `#[laravel::test(app = create)]`에 `create`를 전달합니다.

```rust
// tests/package.rs
use example_package::{InspireConfig, InspireServiceProvider};
use laravel::foundation::ApplicationBuilder;
use laravel::testing::prelude::*;

fn configure() -> ApplicationBuilder {
    Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_providers(|providers| {
            providers.add(InspireServiceProvider);
        })
}

fn create() -> Application {
    configure().create()
}

#[laravel::test(app = create)]
async fn the_package_route_and_assets_work(app: Application) {
    let response = app.get("/inspire").await;

    response.assert_ok();
    assert!(response.header("x-inspiration").is_some());

    app.get("/vendor/inspire/inspire.css")
        .await
        .assert_ok()
        .assert_header("content-type", "text/css");
}
```


`#[laravel::test(app = create)]`는 각 테스트에서 `create()`를 호출하여 새로운 암호화 키와 미설정 항목의 메모리 대체값으로 `testing` 환경의 격리된 앱을 시작합니다. 시작한 `Application` 하나를 공유하지 말고 헬퍼를 추출하세요. 테스트마다 앱을 만들면 세션, 캐시, 시계, 페이크, 설정 재정의가 격리되어 안전한 병렬 실행이 가능합니다.


`configure()`에서 `ApplicationBuilder`를 반환하면 테스트 환경 변수용 `.with_envs(..)`, [migrations](#migrations)를 제공하는 패키지의 `.refresh_database()`, 미들웨어와 주입 서비스를 검증할 호스트 라우트용 `.with_routing(..)` 등 공통 기본값을 한곳에서 설정할 수 있습니다.

```rust
use example_package::{InspireServiceProvider, Quotes};
use laravel::container::Inject;
use laravel::foundation::ApplicationBuilder;
use laravel::testing::prelude::*;

fn configure() -> ApplicationBuilder {
    Application::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_providers(|providers| {
            providers.add(InspireServiceProvider);
        })
        .with_routing(|routing, _| {
            routing.web(|route| {
                route.get("/host", async |quotes: Inject<Quotes>| {
                    quotes.all().join("\n")
                });
            });
        })
}
```


테스트가 `tests/` 아래 여러 파일로 늘어나면 Cargo는 각 파일을 독립 크레이트로 컴파일합니다. `configure()`와 `create()`를 `tests/common/mod.rs`의 `pub` 함수로 옮기고, 각 파일에 `mod common;`을 선언한 뒤 `#[laravel::test]`에 `common::create`를 전달합니다.

```rust
// tests/middleware.rs
mod common;

use laravel::testing::prelude::*;

#[laravel::test(app = common::create)]
async fn web_responses_include_the_inspiration_header(app: Application) {
    let response = app.get("/host").await;

    response.assert_ok();
    assert!(response.header("x-inspiration").is_some());
}
```


특정 테스트에만 환경 변수나 설정 재정의가 필요하면 `#[laravel::test]`의 `Application` 인수를 생략하고 테스트 안에서 `configure()`로 맞춤 앱을 구성합니다.

```rust
#[laravel::test]
async fn disabling_the_header_skips_the_middleware() {
    let response = configure()
        .with_envs([("INSPIRE_HEADER", "false")])
        .create()
        .get("/inspire")
        .await;

    response.assert_ok();
    assert_eq!(response.header("x-inspiration"), None);
}
```


마찬가지로 잘못된 설정을 거부하는 [boot check](#checks-at-boot)를 테스트하려면 `.create().boot().await`를 직접 호출하고 시작 실패를 검증합니다.

```rust
#[laravel::test]
async fn invalid_quotes_stop_the_application_from_booting() {
    let error = configure()
        .with_config(|config, _| {
            config.set(InspireConfig {
                header: true,
                quotes: vec!["Line one\nLine two".to_owned()],
            });
        })
        .create()
        .boot()
        .await
        .expect_err("booting should fail")
        .to_string();

    assert!(error.contains("can't be sent in a header"));
}
```


`cargo test`로 패키지 테스트를 실행합니다. 추가 HTTP 검증, 인증 헬퍼, 하위 시스템 페이크는 [testing guide](/rust/docs/testing)를 참고하세요.