본문으로 건너뛰기
Lottery
Laravel Go 0.x · 한국어 문서https://laravel.com/go/docs/0.x/lottery

Lottery

Introduction​

100개 요청 중 하나에만 진단 정보를 추가 기록하거나 방문자 20명 중 한 명에게 설문을 보여 주는 등 일부 요청에서만 코드를 실행하고 싶을 때가 있습니다. lottery는 지정한 확률로 실행 여부를 결정합니다. Laravel은 내부적으로 요청 100개 중 2개에서 만료된 sessions을 정리할 때 사용합니다.

Drawing​

lottery.Odds(wins, outOf)로 정의하고 당첨 시 true를 반환하는 Draw를 호출하세요. Draw는 요청 r 같은 컨텍스트를 받아 테스트에서 결과를 정할 수 있습니다. 핸들러나 미들웨어 등 어디서나 추첨할 수 있습니다. 다음 대시보드 핸들러는 방문 20회 중 한 번 설문을 보여 줍니다.

package dashboard

import (
"go.laravel.com/inertia"
"go.laravel.com/lottery"
"go.laravel.com/web"
)

func Show(r *web.Request) *web.Response {
return inertia.Render("Dashboard", inertia.Props{
"survey": lottery.Odds(1, 20).Draw(r),
})
}

Draw를 호출할 때마다 새 추첨이므로 같은 사용자도 방문에 따라 설문이 보이거나 보이지 않습니다. 10명 중 한 명에게 새 기능을 공개하는 것처럼 사용자별로 한 번 추첨한 결과를 유지하려면 feature flag 안에서 추첨하세요. Laravel은 사용자별 결과를 저장합니다.

Session cleanup odds​

100번 중 2번인 기본 확률은 대부분의 애플리케이션에 적합합니다. 세션 정리 빈도를 바꾸려면 bootstrap/app.go의 configure function에서 cfg.Session.Lottery를 설정하세요.

func configure(cfg *config.Config, env *config.Env) {
cfg.Session.Lottery = lottery.Odds(1, 50)
}

Testing​

무작위 결과는 테스트를 불안정하게 하므로 테스트의 모든 추첨 결과를 정할 수 있습니다. 클라이언트 생성 시 laraveltest.Lottery를 전달하세요. 다음 테스트는 항상 당첨되어 대시보드가 항상 피드백을 요청하게 합니다.

package feature_test

import (
"testing"

"go.laravel.com/laraveltest"
"go.laravel.com/lottery"

"app/database/factories"
"app/tests"
)

func TestTheDashboardAsksForFeedback(t *testing.T) {
client := tests.New(t, laraveltest.Lottery(lottery.AlwaysWin))
user := client.Create(factories.User)

client.ActingAs(&user).
Get("/dashboard").
AssertInertia("Dashboard").
AssertProp("survey", true)
}

laraveltest.Lottery는 다음 결과 중 하나를 받아 세션 정리와 기능 플래그를 포함한 테스트 애플리케이션의 모든 추첨을 결정합니다.

// Every draw wins, whatever its odds...
laraveltest.Lottery(lottery.AlwaysWin)

// Every draw loses, whatever its odds...
laraveltest.Lottery(lottery.AlwaysLose)

// The next draw wins, then one loses, then draws are random again...
laraveltest.Lottery(lottery.Fix(true, false))

각 테스트는 자체 애플리케이션을 만들므로 한 테스트의 AlwaysWin은 병렬 실행되는 다른 테스트에 영향을 주지 않습니다.

lottery.Fix는 애플리케이션 전체에서 추첨이 발생하는 순서대로 정해진 결과를 제공합니다. HTTP 테스트에서는 핸들러 전에 세션 미들웨어가 정리용 추첨을 하고 shares features with your pages를 수행하는 share 함수도 추첨할 수 있습니다. 핸들러 추첨을 확실히 제어하려면 AlwaysWin이나 AlwaysLose, 또는 특정 플래그를 고정하는 feature.Fake를 사용하세요.