Communitygithub.com

perl-testing

Test2::V0, Test::More, prove 러너, 모킹, Devel::Cover 커버리지 및 TDD 방법론을 사용한 Perl 테스트 패턴. Test2::V0 또는 Test::More로 Perl 테스트를 작성하거나 커버리지를 측정할 때 사용합니다.

perl-testing란 무엇인가요?

이 스킬은 Perl 애플리케이션을 위한 포괄적인 테스트 전략을 제공합니다. Test2::V0, Test::More, prove, TDD 방법론을 기반으로 하며, 레드-그린-리팩터 사이클을 따르는 방법을 설명합니다. Test2::V0의 경우 해시/배열 빌더를 이용한 심층 비교, 서브테스트 격리, 예외 테스트 등을 다루며, Test::More에 대해서는 기본 단언문과 SKIP/TODO 블록 사용법을 포함합니다. 또한 prove 명령어를 통한 테스트 구성과 실행, Devel::Cover를 이용한 커버리지 측정, Test::MockModule을 이용한 모킹 기법도 안내합니다. 마지막으로 done_testing 누락, -l 플래그 미지정, 과도한 모킹 등 일반적인 함정을 피하는 모범 사례를 제시합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/perl-testing

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Perl 테스트 패턴

Test2::V0, Test::More, prove 및 TDD 방법론을 사용한 Perl 애플리케이션의 포괄적인 테스트 전략입니다.

활성화 시점

  • 새 Perl 코드 작성 시 (TDD: 레드, 그린, 리팩터 순서로 진행)
  • Perl 모듈 또는 애플리케이션의 테스트 스위트 설계 시
  • Perl 테스트 커버리지 검토 시
  • Perl 테스트 인프라 구축 시
  • Test::More에서 Test2::V0으로 마이그레이션 시
  • 실패하는 Perl 테스트 디버깅 시

TDD 워크플로

항상 RED-GREEN-REFACTOR 사이클을 따르세요.

# Step 1: RED — 실패하는 테스트 작성
# t/unit/calculator.t
use v5.36;
use Test2::V0;

use lib 'lib';
use Calculator;

subtest 'addition' => sub {
    my $calc = Calculator->new;
    is($calc->add(2, 3), 5, 'adds two numbers');
    is($calc->add(-1, 1), 0, 'handles negatives');
};

done_testing;

# Step 2: GREEN — 최소한의 구현 작성
# lib/Calculator.pm
package Calculator;
use v5.36;
use Moo;

sub add($self, $a, $b) {
    return $a + $b;
}

1;

# Step 3: REFACTOR — 테스트가 통과하는 상태에서 개선
# 실행: prove -lv t/unit/calculator.t

Test::More 기본

표준 Perl 테스트 모듈로, 널리 사용되며 코어에 포함되어 있습니다.

기본 단언문

use v5.36;
use Test::More;

# 미리 계획을 세우거나 done_testing 사용
# plan tests => 5;  # 고정 계획 (선택 사항)

# 동등성
is($result, 42, 'returns correct value');
isnt($result, 0, 'not zero');

# 부울
ok($user->is_active, 'user is active');
ok(!$user->is_banned, 'user is not banned');

# 심층 비교
is_deeply(
    $got,
    { name => 'Alice', roles => ['admin'] },
    'returns expected structure'
);

# 패턴 매칭
like($error, qr/not found/i, 'error mentions not found');
unlike($output, qr/password/, 'output hides password');

# 타입 검사
isa_ok($obj, 'MyApp::User');
can_ok($obj, 'save', 'delete');

done_testing;

SKIP 및 TODO

use v5.36;
use Test::More;

# 조건부로 테스트 건너뛰기
SKIP: {
    skip 'No database configured', 2 unless $ENV{TEST_DB};

    my $db = connect_db();
    ok($db->ping, 'database is reachable');
    is($db->version, '15', 'correct PostgreSQL version');
}

# 예상 실패 표시
TODO: {
    local $TODO = 'Caching not yet implemented';
    is($cache->get('key'), 'value', 'cache returns value');
}

done_testing;

Test2::V0 현대 프레임워크

Test2::V0은 Test::More의 현대적인 대체제로, 더 풍부한 단언문, 더 나은 진단 및 확장성을 제공합니다.

Test2를 선택해야 하는 이유

  • 해시/배열 빌더를 통한 우수한 심층 비교
  • 실패 시 더 나은 진단 출력
  • 더 깔끔한 범위의 서브테스트
  • Test2::Tools::* 플러그인을 통한 확장성
  • Test::More 테스트와 역호환성

빌더를 이용한 심층 비교

use v5.36;
use Test2::V0;

# 해시 빌더 — 부분 구조 검사
is(
    $user->to_hash,
    hash {
        field name  => 'Alice';
        field email => match(qr/\@example\.com$/);
        field age   => validator(sub { $_ >= 18 });
        # 다른 필드는 무시
        etc();
    },
    'user has expected fields'
);

# 배열 빌더
is(
    $result,
    array {
        item 'first';
        item match(qr/^second/);
        item DNE();  # 존재하지 않음 — 추가 항목이 없는지 확인
    },
    'result matches expected list'
);

# Bag — 순서에 무관한 비교
is(
    $tags,
    bag {
        item 'perl';
        item 'testing';
        item 'tdd';
    },
    'has all required tags regardless of order'
);

서브테스트

use v5.36;
use Test2::V0;

subtest 'User creation' => sub {
    my $user = User->new(name => 'Alice', email => '[email protected]');
    ok($user, 'user object created');
    is($user->name, 'Alice', 'name is set');
    is($user->email, '[email protected]', 'email is set');
};

subtest 'User validation' => sub {
    my $warnings = warns {
        User->new(name => '', email => 'bad');
    };
    ok($warnings, 'warns on invalid data');
};

done_testing;

Test2를 이용한 예외 테스트

use v5.36;
use Test2::V0;

# 코드가 죽는지 테스트
like(
    dies { divide(10, 0) },
    qr/Division by zero/,
    'dies on division by zero'
);

# 코드가 살아있는지 테스트
ok(lives { divide(10, 2) }, 'division succeeds') or note($@);

# 결합 패턴
subtest 'error handling' => sub {
    ok(lives { parse_config('valid.json') }, 'valid config parses');
    like(
        dies { parse_config('missing.json') },
        qr/Cannot open/,
        'missing file dies with message'
    );
};

done_testing;

테스트 구성 및 prove

디렉토리 구조

t/
├── 00-load.t              # 모듈 컴파일 확인
├── 01-basic.t             # 핵심 기능
├── unit/
│   ├── config.t           # 모듈별 단위 테스트
│   ├── user.t
│   └── util.t
├── integration/
│   ├── database.t
│   └── api.t
├── lib/
│   └── TestHelper.pm      # 공유 테스트 유틸리티
└── fixtures/
    ├── config.json        # 테스트 데이터 파일
    └── users.csv

prove 명령어

# 모든 테스트 실행
prove -l t/

# 자세한 출력
prove -lv t/

# 특정 테스트 실행
prove -lv t/unit/user.t

# 재귀 검색
prove -lr t/

# 병렬 실행 (8개 작업)
prove -lr -j8 t/

# 마지막 실행에서 실패한 테스트만 실행
prove -l --state=failed t/

# 색상 출력 및 타이머
prove -l --color --timer t/

# CI용 TAP 출력
prove -l --formatter TAP::Formatter::JUnit t/ > results.xml

.proverc 설정

-l
--color
--timer
-r
-j4
--state=save

픽스처 및 설정/정리

서브테스트 격리

use v5.36;
use Test2::V0;
use File::Temp qw(tempdir);
use Path::Tiny;

subtest 'file processing' => sub {
    # 설정
    my $dir = tempdir(CLEANUP => 1);
    my $file = path($dir, 'input.txt');
    $file->spew_utf8("line1\nline2\nline3\n");

    # 테스트
    my $result = process_file("$file");
    is($result->{line_count}, 3, 'counts lines');

    # 정리는 자동으로 이루어집니다 (CLEANUP => 1)
};

공유 테스트 헬퍼

재사용 가능한 헬퍼는 t/lib/TestHelper.pm에 배치하고 use lib 't/lib'로 로드합니다. create_test_db(), create_temp_dir(), fixture_path() 같은 팩토리 함수를 Exporter를 통해 내보냅니다.

모킹

Test::MockModule

use v5.36;
use Test2::V0;
use Test::MockModule;

subtest 'mock external API' => sub {
    my $mock = Test::MockModule->new('MyApp::API');

    # 좋은 예: Mock이 제어된 데이터를 반환
    $mock->mock(fetch_user => sub ($self, $id) {
        return { id => $id, name => 'Mock User', email => '[email protected]' };
    });

    my $api = MyApp::API->new;
    my $user = $api->fetch_user(42);
    is($user->{name}, 'Mock User', 'returns mocked user');

    # 호출 횟수 확인
    my $call_count = 0;
    $mock->mock(fetch_user => sub { $call_count++; return {} });
    $api->fetch_user(1);
    $api->fetch_user(2);
    is($call_count, 2, 'fetch_user called twice');

    # $mock이 범위를 벗어나면 Mock이 자동으로 복원됩니다
};

# 나쁜 예: 복원 없는 몽키 패칭
# *MyApp::API::fetch_user = sub { ... };  # 절대 하지 마세요 — 테스트 간에 누출됩니다

가벼운 Mock 객체가 필요하면 Test::MockObject를 사용하여 주입 가능한 테스트 더블을 만들고 ->mock()으로 호출을 ->called_ok()로 확인하세요.

Devel::Cover를 이용한 커버리지

커버리지 실행

# 기본 커버리지 보고서
cover -test

# 또는 단계별로
perl -MDevel::Cover -Ilib t/unit/user.t
cover

# HTML 보고서
cover -report html
open cover_db/coverage.html

# 특정 임계값
cover -test -report text | grep 'Total'

# CI 친화적: 임계값 미만이면 실패
cover -test && cover -report text -select '^lib/' \
  | perl -ne 'if (/Total.*?(\d+\.\d+)/) { exit 1 if $1 < 80 }'

통합 테스트

데이터베이스 테스트에는 인메모리 SQLite를, API 테스트에는 HTTP::Tiny Mock을 사용하세요.

use v5.36;
use Test2::V0;
use DBI;

subtest 'database integration' => sub {
    my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:', '', '', {
        RaiseError => 1,
    });
    $dbh->do('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');

    $dbh->prepare('INSERT INTO users (name) VALUES (?)')->execute('Alice');
    my $row = $dbh->selectrow_hashref('SELECT * FROM users WHERE name = ?', undef, 'Alice');
    is($row->{name}, 'Alice', 'inserted and retrieved user');
};

done_testing;

모범 사례

권장 사항 (DO)

  • TDD 준수: 구현 전에 테스트를 작성하세요 (레드-그린-리팩터)
  • Test2::V0 사용: 현대적인 단언문, 더 나은 진단
  • 서브테스트 사용: 관련 단언문을 그룹화하고 상태를 격리하세요
  • 외부 의존성 모킹: 네트워크, 데이터베이스, 파일 시스템
  • prove -l 사용: 항상 lib/를 @INC에 포함시키세요
  • 테스트 이름을 명확하게: 'user login with invalid password fails'
  • 경계값 테스트: 빈 문자열, undef, 0, 경계값
  • 80% 이상 커버리지 목표: 비즈니스 로직 경로에 집중하세요
  • 테스트 속도 유지: I/O 모킹, 인메모리 데이터베이스 사용

금지 사항 (DON'T)

  • 구현을 테스트하지 마세요: 내부가 아닌 동작과 출력을 테스트하세요
  • 서브테스트 간 상태 공유 금지: 각 서브테스트는 독립적이어야 합니다
  • done_testing 생략 금지: 계획된 모든 테스트가 실행되었는지 확인합니다
  • 과도한 모킹 금지: 테스트 대상 코드가 아닌 경계만 모킹하세요
  • 새 프로젝트에 Test::More 사용 금지: Test2::V0을 선호하세요
  • 테스트 실패 무시 금지: 병합 전에 모든 테스트가 통과해야 합니다
  • CPAN 모듈 테스트 금지: 라이브러리가 올바르게 작동한다고 신뢰하세요
  • 취약한 테스트 작성 금지: 과도하게 구체적인 문자열 매칭을 피하세요

빠른 참조

작업명령어 / 패턴
모든 테스트 실행prove -lr t/
하나의 테스트 상세 실행prove -lv t/unit/user.t
병렬 테스트 실행prove -lr -j8 t/
커버리지 보고서cover -test && cover -report html
동등성 테스트is($got, $expected, 'label')
심층 비교is($got, hash { field k => 'v'; etc() }, 'label')
예외 테스트like(dies { ... }, qr/msg/, 'label')
예외 없음 테스트ok(lives { ... }, 'label')
메서드 모킹Test::MockModule->new('Pkg')->mock(m => sub { ... })
테스트 건너뛰기SKIP: { skip 'reason', $count unless $cond; ... }
TODO 테스트TODO: { local $TODO = 'reason'; ... }

일반적인 함정

done_testing 누락

# 나쁜 예: 테스트 파일이 실행되지만 모든 테스트가 실행되었는지 확인하지 않음
use Test2::V0;
is(1, 1, 'works');
# done_testing 누락 — 테스트 코드가 건너뛰어지면 조용한 버그 발생

# 좋은 예: 항상 done_testing으로 종료
use Test2::V0;
is(1, 1, 'works');
done_testing;

-l 플래그 누락

# 나쁜 예: lib/에 있는 모듈을 찾을 수 없음
prove t/unit/user.t
# @INC에서 MyApp/User.pm을 찾을 수 없음

# 좋은 예: @INC에 lib/ 포함
prove -l t/unit/user.t

과도한 모킹

테스트 대상 코드가 아닌 의존성을 모킹하세요. 테스트가 단지 Mock이 알려준 값을 반환하는지 확인하는 것이라면 아무것도 테스트하지 않는 것입니다.

테스트 오염

서브테스트 내에서는 my 변수를 사용하고 our는 절대 사용하지 마세요. 상태가 테스트 간에 누출되는 것을 방지합니다.

기억하세요: 테스트는 당신의 안전망입니다. 빠르고 집중적이며 독립적으로 유지하세요. 새 프로젝트에는 Test2::V0, 실행에는 prove, 책임 추적에는 Devel::Cover를 사용하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬