KScript 문서
KO

언어

영어에서 자동 번역되었습니다. 원문은 영어입니다.

테스트

체크

expect은 이름 없이 확인할 값을 먼저 받고, 체크 하나를 받아요: expect($total, equals: 3). 체크에 쓰는 값은 모두 식이므로, 텍스트는 따옴표로 감싸야 해요: equals: 'hello'.

확인 통과 조건
expect($x, equals: 5) ==이 비교하는 방식으로 값이 같을 때 통과해요: '5'가 5와 같아요. 목록과 맵은 항목별로 비교하며, 실패하면 어디가 다른지 알려 줘요.
not_equals: 5 같지 않아요.
same: 5 엄격하게 같아요(===): 타입과 값이 모두 같아요.
contains: 'Joan' 목록이면 항목, 텍스트면 텍스트, 맵이면 키를 나타내요.
not_contains: 'Joan' 반대입니다.
matches: '^\d+$' 텍스트가 정규식과 일치해요.
type: list 값은 string, number, bool, list, map, date, fn 또는 null이에요.
count: 3 목록이나 맵에 그만큼의 항목이 있거나, 텍스트에 그만큼의 문자가 있습니다.
count_at_most: 4 리스트나 맵은 최대 그 개수만큼의 항목을 가지며, 텍스트는 최대 그 개수만큼의 문자를 가집니다. @queries()를 사용하면 테스트가 보낸 쿼리 수를 확인합니다.
close_to: 0.3 이 값과 within: 이내에 있는 수입니다(별도로 지정하지 않으면 0.000000001): expect(0.1 + 0.2, close_to: 0.3), expect($average, close_to: 4.33, within: 0.01). 부동소수점으로 정확히 표현할 수 없는 금액, 통계 및 기타 계산에 사용하세요.
has: { status: 'paid' } 맵에는 다음 키와 값이 있으며, 다른 키도 있을 수 있습니다. 중첩된 맵도 같은 방식으로 확인합니다. 리스트의 경우 모든 항목에 이러한 키가 있어야 합니다.

message: … 검사에서 어떤 값이든 나오면 기본 메시지를 대신합니다.

API 응답에는 테스트가 몇몇 필드만 확인하는 경우 has:가 적합해요.

<let name="order" value="{ id: 7, status: 'paid', total: 30, customer: { name: 'Ann', email: 'ann@example.com' } }" />
<expect value="$order" has="{ status: 'paid', customer: { name: 'Ann' } }" />
<expect value="[{ id: 1, active: true }, { id: 2, active: true }]" has="{ active: true }" />
$order = { id: 7, status: 'paid', total: 30, customer: { name: 'Ann', email: 'ann@example.com' } }
expect($order, has: { status: 'paid', customer: { name: 'Ann' } })
expect([{ id: 1, active: true }, { id: 2, active: true }], has: { active: true })

@assert(condition, message?)는 조건을 확인해요. 단독 줄에서 쓰거나 람다 같은 식 안에서 쓸 수 있어요. 비교가 실패하면 양쪽 각각의 값을 보여줘요:

텍스트
Expected $order.total == 30 to be true.
  $order.total is 25

@fail(message?) 테스트가 바로 실패해요.

오류

expect_error { }는 본문이 오류로 끝나지 않으면 실패합니다. type는 오류 타입을 확인하고(이를 상속한 오류 타입도 포함), contains는 메시지를 확인하며, as는 오류(type, message, line, file, status, cause 및 그 필드)를 이후 검사에 사용할 수 있도록 보관합니다:

<expect_error type="Validation" contains="positive" as="err">
  <do>@set_age(-1)</do>
</expect_error>
<expect value="$err.line" type="number" />
expect_error(type: Validation, contains: 'positive', as: err) {
  @set_age(-1)
}
expect($err.line, type: number)

하나의 식에서는 throws이 더 짧아요. 값을 계산하는 과정이 해당 유형의 오류로 중단되면 통과해요.

<error name="PersonNotFound" extends="NotFound" />

<fn name="find_person" params="id: int">
  <throw type="PersonNotFound">No person with id {$id}</throw>
</fn>

<expect value="@find_person(99)" throws="PersonNotFound" />
<expect value="'nope'->convert(from: json)" throws="Format" /> <!-- Json extends Format -->
error PersonNotFound extends NotFound

fn find_person(id: int) {
  throw PersonNotFound "No person with id {$id}"
}

expect(@find_person(99), throws: PersonNotFound)
expect('nope'->convert(from: json), throws: Format) // Json extends Format

본문 안에서 실패한 검사는 예상된 오류로 처리되지 않고, 여전히 실패로 보고됩니다.

출력 및 입력

capture(into: out) { }는 본문을 실행하고, 출력한 내용을 $out에 넣어요(줄은 마지막 줄을 제외하고 \n로 끝나요). input는 input 같은 프롬프트에 대한 답을 텍스트 또는 줄 목록으로 제공해요:

<capture into="out" input="['Joan', 'yes']">
  <do>@sign_up()</do>
</capture>
<expect value="$out" contains="'Welcome, Joan'" />
capture(into: out, input: ['Joan', 'yes']) {
  @sign_up()
}
expect($out, contains: 'Welcome, Joan')

스크립트 전체

@run_script(path, { args, input })는 다른 스크립트를 독립적으로 실행하고, kscript path args…와 같이 동작하며, { output, code, error }를 반환해요: 출력한 내용, 종료 코드(오류로 멈춘 경우 3), 그리고 오류 또는 null예요. 경로는 테스트 파일을 기준으로 한 상대 경로예요. 스크립트는 프로젝트의 패키지를 사용할 수 있지만, KScript.Test는 사용할 수 없어요.

<test name="hello.kscript greets the name it is given">
  <let name="run" value="@run_script('../scripts/hello.kscript', options: { args: ['Ellie'] })" />
  <expect value="$run.code" equals="0" />
  <expect value="$run.output" equals="'Hello, Ellie!'" />
</test>
test(name: 'hello.kscript greets the name it is given') {
  $run = @run_script('../scripts/hello.kscript', options: { args: ['Ellie'] })
  expect($run.code, equals: 0)
  expect($run.output, equals: 'Hello, Ellie!')
}

최상위 수준에서 작업을 수행하거나 exit을 호출하는 스크립트에 사용하세요. 직접 exit를 호출하는 테스트는 실패합니다.

@check_script(path)는 다른 스크립트를 kscript check가 하는 것처럼 실행하지 않고 검사하며, 문제를 나타나는 순서대로 반환합니다. 반환값은 { line, column, end_line, end_column, severity, code, message, fixes }의 목록이고, fixes에는 편집기가 해당 문제에 대해 제공하는 빠른 수정의 제목이 들어 있습니다. 이를 사용하면 편집기와 kscript check가 잡아내는 실수가 무엇인지 확인할 수 있습니다. 일부러 실수를 넣은 스크립트는 lint.exclude가 제외하는 폴더에 보관하세요(프로젝트 참고). 그래야 프로젝트 전체의 kscript check가 깨끗하게 유지됩니다. @check_script()는 그래도 해당 파일을 검사합니다:

<test name="a map is not a flag">
  <let name="problems" value="@check_script('mistakes/flags.kscript')" />
  <expect value="$problems" count="1" /> <!-- one mistake gets one report -->
  <expect value="$problems[0].line" equals="2" />
  <expect value="$problems[0].message" contains="'needs true or false, but this is a map'" />
</test>
test(name: 'a map is not a flag') {
  $problems = @check_script('mistakes/flags.kscript')
  expect($problems, count: 1)       // one mistake gets one report
  expect($problems[0].line, equals: 2)
  expect($problems[0].message, contains: 'needs true or false, but this is a map')
}

페이지

KScript.Web의 @visit(path)은(는) 브라우저가 받는 것과 같은 프로젝트 페이지를 렌더링하며, kscript serve이(가) 응답하는 방식과 같습니다. 먼저 프로젝트의 라우트(view: 라우트, 또는 @view(...)를 반환하는 컨트롤러, 그리고 해당 미들웨어)를 처리한 뒤, 가장 가까운 kscript.json 아래 serve.root의 파일 페이지를 처리합니다. 라이브 핸들러는 브라우저에서처럼 서버에서 실행되므로, 테스트에서 페이지를 클릭하며 진행할 수 있습니다:

  • ->click(text)는 해당 텍스트가 있는 버튼이나 링크의 클릭 핸들러를 실행해요(또는 aria-label 또는 title).
  • ->change(text)는 <label>에 해당 텍스트가 있는 입력의 변경 핸들러를 실행해요. 예를 들어 체크박스가 있어요.
  • ->fill(field, value)는 해당 필드에 바인딩된 입력란에 입력하고, ->submit(text?)는 폼의 on-submit을 실행해요.
  • 라이브 핸들러가 없는 일반 HTML 폼에서 ->fill(name, value)는 해당 name를 가진 필드에 입력하고, ->submit(text?)는 브라우저처럼 폼을 보내요. 페이지가 가진 모든 이름 있는 필드(숨김 필드, CSRF _token, 체크된 상자, select의 선택된 옵션)를 입력한 값과 함께, 그리고 해당 텍스트의 버튼을 폼의 action와 method로 보내요. 텍스트가 없으면 입력해 둔 폼을 보내요. 응답의 리다이렉트는 따라가므로, .path는 브라우저가 도착할 곳이에요.
  • .text는 페이지에 있는 단어이고, .html는 그 HTML이며, ->classes(text)는 그 텍스트를 가진 요소의 클래스입니다.

이들은 각각 페이지를 반환하므로 연결해서 쓸 수 있어요. 테스트가 호출하는 동안 라우트가 디스패치하는 작업은 테스트 자체의 작업과 마찬가지로 즉시 실행돼요(작업 테스트하기 참고). 페이지가 없으면 NotFound 오류예요. 핸들러가 @emit_event()(또는 emit:)로 보내는 이벤트는 브라우저에서처럼 다른 블록의 on-event 리스너에 전달돼요. target:가 지정한 블록이나, 듣고 있는 모든 블록에 전달돼요.

경로를 방문하면 앱이 설정한 쿠키(게스트 쿠키, 세션)가 해당 클릭에 대해 유지되며, 브라우저와 같이 리다이렉트를 따라갑니다: .path는 최종 도착 지점입니다. @acting_as()는 방문을 로그인 상태로 표시하며, @api(/...)에서도 그렇게 합니다. @visit(path, { headers: { Cookie: 'guest=abc' } })는 자체 헤더를 전송합니다(bearer:는 토큰을 전송합니다):

<import package="KScript.Web" />
<import package="KScript.Auth" />

<test name="a guest is sent to sign in">
  <expect value="@visit('/account').path" equals="'/login'" />
</test>

<test name="the account page makes a token">
  <do>@acting_as(@register('ada@example.test', 'correct-horse-battery-9'))</do>
  <let name="page" value="@visit('/account')->fill('name', 'laptop')->submit('Make a token')" />
  <expect value="$page.text" contains="'Your new token is'" />
</test>
import KScript.Web
import KScript.Auth

test(name: 'a guest is sent to sign in') {
  expect(@visit('/account').path, equals: '/login')
}

test(name: 'the account page makes a token') {
  @acting_as(@register('ada@example.test', 'correct-horse-battery-9'))
  $page = @visit('/account')->fill('name', 'laptop')->submit('Make a token')
  expect($page.text, contains: 'Your new token is')
}
<import package="KScript.Web" />

<test name="adding a task clears the box">
  <let name="page" value="@visit('/tasks')->fill('draft', 'Write the docs')->submit()" />
  <expect value="$page.text" contains="'Write the docs'" />
  <expect value="$page->classes('Write the docs')" not_contains="'done'" />
</test>
import KScript.Web

test(name: 'adding a task clears the box') {
  $page = @visit('/tasks')->fill('draft', 'Write the docs')->submit()
  expect($page.text, contains: 'Write the docs')
  expect($page->classes('Write the docs'), not_contains: 'done')
}

samples/task-board에는 모든 버튼이 핸들러 축약 표기법으로 작성된 페이지가 있으며, 각 버튼마다 테스트가 있어요.