Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

class AssertionCtx

public class AssertionCtx {}

功能:存储用户定义的断言的状态。提供用于编写​​用户定义断言的方法。

prop args

public prop args: String

功能:返回以逗号分隔的未解析的用户定义断言参数的字符串。

类型: String

prop caller

public prop caller: String

功能:获取用户定义的断言函数的标识符。

类型: String

prop hasErrors

public prop hasErrors: Bool

功能:如果用户定义内的任何断言失败,则为 true 。否则为 false

类型: Bool

func arg(String)

public func arg(key: String): String

功能:返回表示原始传递的标识符的参数值的字符串表达,与参数列表中的标识符匹配。

参数:

  • key: String - 函数参数列表中的标识符。

返回值:

  • String - 对应标识符的参数值字符串表达。

func fail(String)

public func fail(message: String): Nothing 

功能:存储失败信息,在用户定义的断言函数中提供并抛出 AssertExpection

参数:

  • message: String - 失败信息。

func fail<PP>(PP)

public func fail<PP>(pt: PP): Nothing where PP <: PrettyPrintable

功能:存储失败信息,在用户定义的断言函数中提供并抛出 AssertExpection

参数:

func failExpect(String)

public func failExpect(message: String): Unit 

功能:存储失败信息,在用户定义的断言函数内提供并继续函数执行。

参数:

  • message: String - 失败信息。

func failExpect<PP>(PP)

public func failExpect<PP>(pt: PP): Unit where PP <: PrettyPrintable

功能:存储失败信息,在用户定义的断言函数内提供并继续函数执行。

参数:

func setArgsAliases(Array<String>)

public func setArgsAliases(aliases: Array<String>): Unit

功能:设置别名以通过函数 arg 访问未解析的用户定义的断言函数参数。框架内部使用,用户无需使用该函数。

参数:

class Benchmark

public class Benchmark {}

功能:该类提供创建和运行单个性能测试用例的方法。

示例:

import std.unittest.*

main() {
    let conf = Configuration()
    conf.set(KeyWarmup.warmup, Duration.Zero)
    conf.set(KeyMinDuration.minDuration, Duration.nanosecond)
    let bench = Benchmark.create("ordinary", configuration: conf, body: {=>})

    println("Running ${bench.name}...") // Prints: Running ordinary...
    bench.run().reportTo(ConsoleReporter())
    let parametrized = Benchmark.createParameterized(
        "parametrized",
        [1, 2, 3],
        configuration: conf,
        body: {_ =>}
    )

    println("Running ${parametrized.name}...")
    parametrized.run().reportTo(ConsoleReporter())
}

可能的运行结果:

Running ordinary...
Starting the benchmark `TestCase_ordinary.ordinary()`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 5.670 us.

--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 275407 ns, RESULT:
    TCS: TestCase_ordinary, time elapsed: 270977 ns, RESULT:
    | Case     | Median |    Err |   Err% |   Mean |
    |:---------|-------:|-------:|-------:|-------:|
    | ordinary |   0 ns |  ±0 ns |  ±0.0% |   0 ns |
    [ PASSED ] CASE: ordinary (48166 ns)
Summary: TOTAL: 1
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 0
--------------------------------------------------------------------------------------------------
Running parametrized...
Starting the benchmark `TestCase_parametrized.parametrized(1)`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 13.42 us.

Starting the benchmark `TestCase_parametrized.parametrized(2)`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 11.85 us.

Starting the benchmark `TestCase_parametrized.parametrized(3)`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 0.910 us.

--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 202400 ns, RESULT:
    TCS: TestCase_parametrized, time elapsed: 198092 ns, RESULT:
    | Case         | Args   | Median |       Err |   Err% |     Mean |
    |:-------------|:-------|-------:|----------:|-------:|---------:|
    | parametrized | 1      |   0 ns | ±206.0 ns |  ±inf% | 112.9 ns |
    | parametrized | 2      |   0 ns | ±35.23 ns |  ±inf% | 7.549 ns |
    | parametrized | 3      |   0 ns | ±46.55 ns |  ±inf% | 25.53 ns |
    [ PASSED ] CASE: parametrized (13302 ns)
Summary: TOTAL: 1
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 0
--------------------------------------------------------------------------------------------------

prop name

public prop name: String

功能:获取用例名称。

类型:String

func run()

public func run(): BenchReport

功能:运行该性能用例。

返回值:

static func create(String, Configuration, Measurement, () -> Unit)

public static func create(
    name: String,
    configuration!: Configuration = Configuration(),
    measurement!: Measurement = TimeNow(),
    body!: () -> Unit
): Benchmark

功能:创建一个性能测试用例对象。

参数:

  • name: String - 用例名称。
  • configuration!: Configuration - 用例配置信息。
  • measurement: Measurement - 测量方法信息。
  • body: () -> Unit - 用例执行体。

返回值:

static func createParameterized<T>(String, DataStrategy<T>, Configuration, Measurement, (T) -> Unit)

public static func createParameterized<T>(
    name: String,
    strategy: DataStrategy<T>,
    configuration!: Configuration = Configuration(),
    measurement!: Measurement = TimeNow(),
    body!: (T) -> Unit
): Benchmark

功能:创建一个参数化的性能测试用例对象。

参数:

  • name: String - 用例名称。
  • strategy: DataStrategy - 参数数据策略。
  • configuration: Configuration - 用例配置信息。
  • measurement!: Measurement 测量方法信息。
  • body: () -> Unit - 用例执行体。

返回值:

static func createParameterized<T>(String, DataStrategyProcessor<T>, Configuration, Measurement, (T) -> Unit)

public static func createParameterized<T>(
    name: String,
    strategy: DataStrategyProcessor<T>,
    configuration!: Configuration = Configuration(),
    measurement!: Measurement = TimeNow(),
    body!: (T) -> Unit
): Benchmark

功能:创建一个参数化的性能测试用例对象。

参数:

返回值:

class BenchReport

public class BenchReport <: Report {}

功能:提供性能用例执行结果报告处理能力。

父类型:

示例:

import std.unittest.*
import std.unittest.testmacro.*
import std.time.*
import std.sync.*

foreign func usleep(arg: UIntNative): UIntNative

@Test
class FooTest {
    @Bench[x in [ 1 ]]
    @Configure[minDuration: Duration.second]
    func testSleep(x: Int64): Unit {
        unsafe { usleep(30000) }
    }
}

main() {
    let startTime = DateTime.now()
    let report: BenchReport = FooTest().asTestSuite().runBenchmarks()
    let duration = DateTime.now() - startTime
    report.reportTo(ConsoleReporter(colored: false))

    let results = report.reportTo(RawStatsReporter())["testSleep1"]
    @Assert(results[0] < 50_000000.0 && results[0] > 25_000000.0)
}

func reportTo<T>(Reporter<BenchReport, T>)

public func reportTo<T>(reporter: Reporter<BenchReport, T>): T

功能:打印性能用例结果报告。

参数:

返回值:

  • T - 打印结果返回值。一般为 Unit 类型。

class CartesianProductProcessor<T0,T1>

public class CartesianProductProcessor<T0, T1> <: DataStrategyProcessor<(T0, T1)> {
    public CartesianProductProcessor(let left: DataStrategyProcessor<T0>, let right: DataStrategyProcessor<T1>)
}

功能:笛卡尔积处理器。

父类型:

CartesianProductProcessor(DataStrategyProcessor<T0>, DataStrategyProcessor<T1>)

public CartesianProductProcessor(let left: DataStrategyProcessor<T0>, let right: DataStrategyProcessor<T1>)

功能:CartesianProductProcessor 构造函数。

参数:

class ConsoleReporter

public class ConsoleReporter <: Reporter<TestReport, Unit> & Reporter<BenchReport, Unit>{
    public ConsoleReporter(let colored!: Bool = true)
}

功能:打印单元测试用例结果或者性能测试用例结果到控制台。

父类型:

示例:

import std.unittest.*
import std.unittest.testmacro.*

main() {
    let testCase = UnitTestCase.create("testCase", body: {
        => @Fail("failing test")
    })
    let report = testCase.run()
    report.reportTo(ConsoleReporter())
}

可能的运行结果:

--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 323478 ns, RESULT:
    TCS: TestCase_testCase, time elapsed: 317308 ns, RESULT:
    [ FAILED ] CASE: testCase (53267 ns)
    Assert Failed: `(failing test)`

Summary: TOTAL: 1
    PASSED: 0, SKIPPED: 0, ERROR: 0
    FAILED: 1, listed below:
            TCS: TestCase_testCase, CASE: testCase
--------------------------------------------------------------------------------------------------

ConsoleReporter(Bool)

public ConsoleReporter(let colored!: Bool = true)

功能:ConsoleReporter 构造函数。

参数:

  • colored!: Bool - 是否使用带颜色的打印,默认带颜色。

class TextReporter<PP>

public class TextReporter<PP> <: Reporter<TestReport, PP> & Reporter<BenchReport, PP> where PP <: PrettyPrinter {
    public TextReporter(let into!: PP)
}

功能:将单元测试用例结果或性能测试结果打印到 PrettyPrinter 的子类。格式与 ConsoleReporter 相同。

父类型:

示例:

import std.unittest.common.*
import std.unittest.*
import std.unittest.testmacro.*

main() {
    let testCase = UnitTestCase.create("testCase", body: {
        => @Fail("failing test")
    })
    let report = testCase.run()
    let pp = PrettyText()
    report.reportTo(TextReporter(into: pp))
    println(pp.toString())
}

可能的运行结果:

--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 331021 ns, RESULT:
    TCS: TestCase_testCase, time elapsed: 322025 ns, RESULT:
    [ FAILED ] CASE: testCase (41768 ns)
    Assert Failed: `(failing test)`

Summary: TOTAL: 1
    PASSED: 0, SKIPPED: 0, ERROR: 0
    FAILED: 1, listed below:
            TCS: TestCase_testCase, CASE: testCase
--------------------------------------------------------------------------------------------------

TextReporter(PP)

public TextReporter(let into!: PP)

功能:TextReporter 构造函数。

参数:

class CsvReporter

public class CsvReporter <: Reporter<BenchReport, Unit> {
    public CsvReporter(let directory: Path)
}

功能:打印性能测试用例结果数据到 CSV 文件上。

父类型:

示例:

import std.fs.*
import std.unittest.*

main() {
    let conf = Configuration()
    conf.set(KeyWarmup.warmup, Duration.Zero)
    conf.set(KeyMinDuration.minDuration, Duration.nanosecond)
    let bench = Benchmark.create("bench", configuration: conf, body: {=>})
    bench.run().reportTo(CsvReporter(Path(".")))
    let report = File.readFrom("./benchmarks/bench-default.TestCase_bench.csv") |> String.fromUtf8
    println(report)
}

可能的运行结果:

Starting the benchmark `TestCase_bench.bench()`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 6.000 us.

Case,Args,Median,Err,Err%,Mean,Unit,Measurement
"bench",,"0.000000","38.153846","inf","7.576368","ns","Duration"

CsvReporter(Path)

public CsvReporter(let directory: Path)

功能:CsvReporter 构造函数。

参数:

  • directory: Path - 打印文件生成地址。

class CsvRawReporter

public class CsvRawReporter <: Reporter<BenchReport, Unit> {
    public CsvRawReporter(let directory: Path)
}

功能:打印性能测试用例结果数据,该数据只有批次的原始测量值,到 CSV 文件上。

父类型:

示例:

import std.fs.*
import std.unittest.*

main() {
    let conf = Configuration()
    conf.set(KeyWarmup.warmup, Duration.Zero)
    conf.set(KeyMinDuration.minDuration, Duration.nanosecond)
    let bench = Benchmark.create("bench", configuration: conf, body: {=>})
    bench.run().reportTo(CsvRawReporter(Path(".")))
    let report = File.readFrom("./benchmarks/bench-default.TestCase_bench.csv") |> String.fromUtf8
    println(report)
}

可能的运行结果:

Starting the benchmark `TestCase_bench.bench()`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 7.330 us.

Case,Args,BatchSize,Duration,Unit,Measurement
"bench",,"1","256.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","256.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","256.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"1","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"
"bench",,"0","0.000000","ns","Duration"

CsvRawReporter(Path)

public CsvRawReporter(let directory: Path)

功能:CsvRawReporter 构造函数。

参数:

  • directory: Path - 打印文件生成地址。

class DataStrategyProcessor<T>

sealed abstract class DataStrategyProcessor<T> {}

功能:所有 DataStrategy 组件的基类。该类的实例由 @Strategy 宏或成员函数创建。

prop isInfinite

protected prop isInfinite: Bool 

功能:获取该策略是否为无限。

类型:Bool

func intoBenchmark(String, Configuration, (T, Int64, Int64) -> Float64)

public func intoBenchmark(
    caseName!: String,
    configuration!: Configuration,
    doRun!: (T, Int64, Int64) -> Float64
): Benchmark

功能:宏生成的代码使用的辅助函数。用于创建使用该策略的性能测试用例。

参数:

  • caseName!: String - 用例名称。
  • configuration!: Configuration - 配置信息。
  • doRun!: (T, Int64, Int64) -> Float64 - 性能测试用例执行体。

返回值:

func intoUnitTestCase(String, Configuration, (T) -> Unit)

public func intoUnitTestCase(
    caseName!: String,
    configuration!: Configuration,
    doRun!: (T) -> Unit
): UnitTestCase

功能:宏生成的代码使用的辅助函数。用于创建使用该策略的测试用例。

参数:

  • caseName!: String - 用例名称。
  • configuration!: Configuration - 配置信息。
  • doRun!: (T) -> Unit - 性能测试用例执行体。

返回值:

func lastItemInfo()

protected func lastItemInfo(): Array<InputParameter>

功能:获取上一个处理条目的信息。

返回值:

func lastItem(Configuration)

protected func lastItem(configuration: Configuration): T

功能:获取上一个处理条目。

参数:

返回值:

  • T - 上一个处理条目。

func provide(Configuration)

protected func provide(configuration: Configuration): Iterable<T>

功能:生成依据配置信息和数据策略生成的数据迭代器。

参数:

返回值:

func shrinkLastItem(Configuration, LazyCyclicNode)

protected func shrinkLastItem(configuration: Configuration, engine: LazyCyclicNode): Iterable<T>

功能:收缩上一个条目。

参数:

返回值:

  • Iterable<T> - 收缩后的数据迭代器。

static func start(DataStrategy<T>, String)

public static func start(s: DataStrategy<T>, name: String): SimpleProcessor<T>

功能:DataStrategy 的组合和映射的起点。

参数:

返回值:

static func start<U>(() -> DataStrategy<U>, String)

public static func start<U>(
    f: () -> DataStrategy<U>,
    name: String
): DataStrategyProcessor<U> where U <: BenchInputProvider < T >

功能:DataStrategy 的组合和映射的起点。

参数:

  • f: () -> DataStrategy<U> - 生成数据策略的闭包。
  • name: String - 用例名称。

返回值:

static func start(() -> DataStrategy<T>, String, Int64)

public static func start(
    f: () -> DataStrategy<T>,
    name: String,
    x!: Int64 = 0
): SimpleProcessor<T>

功能:DataStrategy 的组合和映射的起点。

参数:

  • s: () -> DataStrategy<T> - 生成数据策略的闭包。
  • name: String - 用例名称。
  • x!: Int64 - 为实现不同返回值的重构增加的参数。

返回值:

static func start(() -> DataStrategyProcessor<T>, String)

public static func start(f: () -> DataStrategyProcessor<T>, _: String): DataStrategyProcessor<T>

功能:DataStrategy 的组合和映射的起点。

参数:

返回值:

static func start<U>(() -> DataStrategyProcessor<U>, String, Int64)

public static func start<U>(
    f: () -> DataStrategyProcessor<U>,
    _: String,
    x!: Int64 = 0
): DataStrategyProcessor<U> where U <: BenchInputProvider<T>

功能:DataStrategy 的组合和映射的起点。

参数:

  • s: () -> DataStrategyProcessor<U> - 生成数据策略处理器的闭包。
  • name: String - 用例名称。
  • x!: Int64 - 为实现不同返回值的重构增加的参数。

返回值:

extend <T> DataStrategyProcessor<T>

extend <T> DataStrategyProcessor<T> {}

func map<R>((T) -> R)

public func map<R>(f: (T) -> R): MapProcessor<T, R>

功能:简单地将 f 应用于原始数据策略的每个项目。 Shrink 也会发生在原始输入上,然后进行映射。

参数:

  • f: (T) -> R - 需要增加的处理逻辑函数。

返回值:

func mapWithConfig<R>((T, Configuration) -> R)

public func mapWithConfig<R>(f: (T, Configuration) -> R): MapProcessor<T, R>

功能:可以访问当前的 Configuration ,只需将 f 应用于原始数据策略的每个项目。 Shrink 也会发生在原始输入上,然后进行映射。

参数:

  • f: (T, Configuration) -> R - 需要增加的处理逻辑函数。

返回值:

func flatMap<R>((T) -> DataProvider<R>)

public func flatMap<R>(f: (T) -> DataProvider<R>): FlatMapProcessor<T, R>

功能:简单地将 f 应用于原始数据策略的每个项目,然后展平结果。 Shrink 也会发生在原始输入上,然后进行 flatMap

参数:

  • f: (T) -> DataProvider<R> - 需要增加的处理逻辑函数。

返回值:

func flatMapStrategy((T) -> DataStrategy<R>)

public func flatMapStrategy<R>(f: (T) -> DataStrategy<R>): FlatMapStrategyProcessor<T, R>

功能:简单地将 f 应用于原始数据策略的每个项目,然后展平结果。 Shrink 是通过返回的策略而不是原始输入来完成的。

参数:

  • f: (T) -> DataStrategy<R> - 需要增加的处理逻辑函数。

返回值:

func product(DataStrategyProcessor<R>)

public func product<R>(p: DataStrategyProcessor<R>): CartesianProductProcessor<T, R>

功能:笛卡尔积组合器创建包含原始策略中元素的所有可能排列的数据策略。 对于无限策略,它首先迭代所有有限的子策略,然后才推进无限的子策略。 Shrink 独立且统一地发生在原始策略的每个元素上。

参数:

返回值:

func productWithUnit<P>(P): MapProcessor<(T, Unit), T>

public func productWithUnit<P>(p: P): MapProcessor<(T, Unit), T> where P <: DataStrategyProcessor<Unit>

功能:DataStrategyProcessor 的便捷适配器。

参数:

  • p: P - 数据策略处理器。

返回值:

class FlatMapProcessor<T,R>

public class FlatMapProcessor<T,R> <: DataStrategyProcessor<R> {}

功能:对参数数据进行 FlatMap 的处理器。

父类型:

class FlatMapStrategyProcessor<T,R>

public class FlatMapStrategyProcessor<T,R> <: DataStrategyProcessor<R> {}

功能:对参数数据进行 FlatMap 的处理器。

父类型:

class InputParameter

public class InputParameter {}

功能:入参对象类型。

class LazyCyclicNode

public open class LazyCyclicNode {}

功能:用于在一个循环中一个接一个地推进类型擦除的内部惰性迭代器。

func advance()

protected open func advance(): ?Unit

功能:前进一个值。

返回值:

  • ?Unit - 当无法前进时返回 None ,否则返回 Unit 。

func recover()

protected open func recover(): Unit

功能:恢复或后退一个值。

class MapProcessor<T,R>

public class MapProcessor<T,R> <: DataStrategyProcessor<R> {}

功能:对参数数据进行 Map 的处理器。

父类型:

class PowerAssertDiagramBuilder

public class PowerAssertDiagramBuilder {
    public init(expression: String)
}

功能:PowerAssert 输出结果构造器。

init(String)

public init(expression: String)

功能:构造函数。

参数:

  • expression: String - 表达式字符串。

func r<T>(T, String, Int64)

public func r<T>(
    value: T,
    exprAsText: String,
    position: Int64
): T 

功能:记录对比数据。

参数:

  • value: T - 被记录的数据。
  • exprAsText: String - 表达式字符串。
  • position: Int64 - 位置信息。

返回值:

  • T - 被记录的数据。

func r(String, String, Int64)

public func r(
    value: String,
    exprAsText: String,
    position: Int64
): String

功能:记录对比数据。

参数:

  • value: String - 被记录的数据。
  • exprAsText: String - 表达式字符串。
  • position: Int64 - 位置信息。

返回值:

  • String - 被记录的数据。

func r(Rune, String, Int64)

public func r(
    value: Rune,
    exprAsText: String,
    position: Int64
): Rune

功能:记录对比数据。

参数:

  • value: Rune - 被记录的数据。
  • exprAsText: String - 表达式字符串。
  • position: Int64 - 位置信息。

返回值:

  • Rune - 被记录的数据。

func h(Exception, String, Int64)

public func h(
    exception: Exception,
    exprAsText: String,
    position: Int64
): Nothing

功能:处理异常。

参数:

  • exception: Exception - 需要被处理的异常。
  • exprAsText: String - 表达式字符串。
  • position: Int64 - 位置信息。

func w(Bool)

public func w(passed: Bool): Unit

功能:当用例通过时返回成功结果,失败时抛出异常并打印对比结果。

参数:

  • passed: Bool - 用例是否通过。

class Report

sealed abstract class Report {}

功能:打印测试用例结果报告的基类。

示例:

import std.unittest.*
import std.unittest.testmacro.*

main() {
    let suite = TestSuite
        .builder("tests")
        .add(UnitTestCase.create("case1", body: {=> @Fail("failing case")}))
        .add(UnitTestCase.create("case2", body: {=> @Assert(1 + 2, 3)}))
        .build()
    let report = suite.runTests()
    println("Cases: ${report.caseCount}")
    println("Skipped: ${report.skippedCount}")
    println("Passed: ${report.passedCount}")
    println("Errors: ${report.errorCount}")
    println("Failed: ${report.failedCount}")
}

可能的运行结果:

Cases: 2
Skipped: 0
Passed: 1
Errors: 0
Failed: 1

prop errorCount

public prop errorCount: Int64

功能:获取错误的用例个数。

类型:Int64

prop caseCount

public prop caseCount: Int64

功能:获取用例个数。

类型:Int64

prop passedCount

public prop passedCount:   Int64

功能:获取通过的用例个数。

类型:Int64

prop failedCount

public prop failedCount:   Int64

功能:获取失败的用例个数。

类型:Int64

prop skippedCount

public prop skippedCount:   Int64

功能:获取跳过的用例个数。

类型:Int64

class RawStatsReporter

public class RawStatsReporter <: Reporter<BenchReport, HashMap<String, (Float64, Float64)>> {
    public RawStatsReporter()
}

功能:未处理的性能测试数据报告器。仅给框架内部使用。

父类型:

RawStatsReporter()

public RawStatsReporter()

功能:RawStatsReporter 构造函数。

class SimpleProcessor<T>

public class SimpleProcessor<T> <: DataStrategyProcessor<T> {
    public SimpleProcessor(let buildDelegate:() -> DataStrategy<T>, let name: String)
}

功能:简单的数据策略处理器。对 DataStrategyProcessor 的一种实现。

父类型:

SimpleProcessor(() -> DataStrategy<T>, String)

public SimpleProcessor(let buildDelegate:() -> DataStrategy<T>, let name: String)

功能:SimpleProcessor 构造函数。

参数:

  • buildDelegate: () -> DataStrategy<T> - 生成数据策略的闭包。
  • name: String - 处理器名称。

class TestGroup

public class TestGroup {}

功能:提供构建和运行测试组合方法的类。

示例:

import std.unittest.*
import std.unittest.testmacro.*

main() {
    let suite1 = TestSuite
        .builder("tests")
        .add(UnitTestCase.create("case1", body: {=> @Fail("failing case")}))
        .add(UnitTestCase.create("case2", body: {=> @Assert(1 + 2, 3)}))
        .build()
    let suite2 = TestSuite.builder("benchmarks").add(Benchmark.create("bench", body: {=>})).build()
    let group = TestGroup.builder("group").add(suite1).add(suite2).build()

    println("Running ${group.name}...")
    group.runTests().reportTo(ConsoleReporter())

    let conf = Configuration()
    conf.set(KeyWarmup.warmup, Duration.Zero)
    conf.set(KeyMinDuration.minDuration, Duration.nanosecond)
    group.runBenchmarks(conf).reportTo(ConsoleReporter())
}

可能的运行结果:

Running group...
--------------------------------------------------------------------------------------------------
TP: group, time elapsed: 298091 ns, RESULT:
    TCS: tests, time elapsed: 290964 ns, RESULT:
    [ PASSED ] CASE: case2 (8340 ns)
    [ FAILED ] CASE: case1 (35797 ns)
    Assert Failed: `(failing case)`

    TCS: benchmarks, No test functions found
Summary: TOTAL: 2
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 1, listed below:
            TCS: tests, CASE: case1
--------------------------------------------------------------------------------------------------
Starting the benchmark `benchmarks.bench()`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 6.410 us.

--------------------------------------------------------------------------------------------------
TP: group, time elapsed: 83094 ns, RESULT:
    TCS: tests, No test functions found
    TCS: benchmarks, time elapsed: 77760 ns, RESULT:
    | Case   | Median |    Err |   Err% |   Mean |
    |:-------|-------:|-------:|-------:|-------:|
    | bench  |   0 ns |  ±0 ns |  ±0.0% |   0 ns |
    [ PASSED ] CASE: bench (2716 ns)
Summary: TOTAL: 1
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 0
--------------------------------------------------------------------------------------------------

prop name

public prop name: String

功能:获取测试组合名称。

类型:String

func runBenchmarks()

public func runBenchmarks(): BenchReport

功能:运行所有性能测试用例。

返回值:

func runBenchmarks(Configuration)

public func runBenchmarks(Configuration): BenchReport

功能:带运行配置得执行所有性能测试用例。

参数:

返回值:

func runTests()

public func runTests(): TestReport

功能:执行所有单元测试用例。

返回值:

func runTests(Configuration)

public func runTests(configuration: Configuration): TestReport

功能:带运行配置得执行所有单元测试用例。

参数:

返回值:

static func builder(String)

public static func builder(name: String): TestGroupBuilder

功能:创建测试组合构造器。

参数:

  • name: String - 测试组合名称。

返回值:

static func builder(TestGroup)

public static func builder(group: TestGroup): TestGroupBuilder

功能:创建测试组合构造器。

参数:

返回值:

class TestGroupBuilder

public class TestGroupBuilder {}

功能:提供配置测试组合的方法的构造器。

请看示例: TestGroup.

func add(Benchmark)

public func add(benchmark: Benchmark): TestGroupBuilder

功能:为测试组合增加性能测试用例。

参数:

  • benchmark: Benchmark - 性能测试用例。

返回值:

func add(TestSuite)

public func add(suite: TestSuite): TestGroupBuilder

功能:为测试组合增加单元测试套。

参数:

返回值:

func add(UnitTestCase)

public func add(test: UnitTestCase): TestGroupBuilder

功能:为测试组合增加单元测试用例。

参数:

返回值:

func build()

public func build(): TestGroup

功能:配置完成后,构建测试组合对象。

返回值:

func configure(Configuration)

public func configure(configuration: Configuration): TestGroupBuilder

功能:为测试组合配置配置信息。

参数:

返回值:

func setName(String)

public func setName(name: String): TestGroupBuilder

功能:为测试组合设置名称。

参数:

返回值:

class TestPackage

public class TestPackage {
    public TestPackage(let name: String)
}

功能:用例包对象。

TestPackage(String)

public TestPackage(let name: String)

功能:TestPackage 构造函数。

参数:

  • name: String - 用例包名称。

func registerCase(() -> UnitTestCase)

public func registerCase(testCase: () -> UnitTestCase): Unit

功能:注册单元测试用例。

参数:

  • testCase: () -> UnitTestCase - 单元测试用例生成闭包。

func registerSuite(() -> TestSuite)

public func registerSuite(suite: () -> TestSuite): Unit

功能:注册测试套。

参数:

  • suite: () -> TestSuite - 测试套生成闭包。

func registerBench(() -> Benchmark)

public func registerBench(bench: () -> Benchmark): Unit

功能:注册性能用例。

参数:

  • bench: () -> Benchmark - 性能用例生成闭包。

func enableOptimizedMockForBench()

public func enableOptimizedMockForBench(): Unit

功能:启用优化以在测试中同时使用模拟和基准测试。

class TestReport

public class TestReport <: Report {}

功能:单元测试执行结果报告。

父类型:

func reportTo<T>(Reporter<TestReport, T>)

public func reportTo<T>(reporter: Reporter<TestReport, T>): T

功能:打印单元测试执行报告。

参数:

返回值:

  • T - 打印返回值,一般为 Unit 。

class TestSuite

public class TestSuite {}

功能:提供构建和执行测试套方法的类。

示例:

import std.unittest.*
import std.unittest.testmacro.*

main() {
    let template = TestSuite
        .builder("template")
        .beforeEach({=> println("Starting case!")})
        .afterEach({name => println("Finished with ${name}")})
        .build()
    let suite = TestSuite
        .builder("suite")
        .template(template)
        .add(UnitTestCase.create("case1", body: {=> @Fail("failing case")}))
        .add(UnitTestCase.create("case2", body: {=> @Assert(1 + 2, 3)}))
        .add(Benchmark.create("bench", body: {=>}))
        .beforeAll({=> println("All tests are about to run!")})
        .afterAll({=> println("All tests are finished!")})
        .build()

    println("Running tests from ${suite.name}...")
    suite.runTests().reportTo(ConsoleReporter())

    println("Running benchmarks from ${suite.name}...")
    let conf = Configuration()
    conf.set(KeyWarmup.warmup, Duration.Zero)
    conf.set(KeyMinDuration.minDuration, Duration.nanosecond)
    suite.runBenchmarks(conf).reportTo(ConsoleReporter())
}

可能的运行结果:

Running tests from suite...
All tests are about to run!
Starting case!
Finished with case1
Starting case!
Finished with case2
All tests are finished!
--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 349990 ns, RESULT:
    TCS: suite, time elapsed: 344021 ns, RESULT:
    [ PASSED ] CASE: case2 (10200 ns)
    [ FAILED ] CASE: case1 (38423 ns)
    Assert Failed: `(failing case)`

Summary: TOTAL: 2
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 1, listed below:
            TCS: suite, CASE: case1
--------------------------------------------------------------------------------------------------
Running benchmarks from suite...
All tests are about to run!
Starting case!
Starting the benchmark `suite.bench()`.
    Warming up for 0 ns.
    Starting measurements of 10 batches. Measuring Duration.
    Max batch size: 1, estimated execution time: 15.33 us.

Finished with bench
All tests are finished!
--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 107250 ns, RESULT:
    TCS: suite, time elapsed: 106224 ns, RESULT:
    | Case   | Median |       Err |   Err% |     Mean |
    |:-------|-------:|----------:|-------:|---------:|
    | bench  |   0 ns | ±42.67 ns |  ±inf% | 15.50 ns |
    [ PASSED ] CASE: bench (5316 ns)
Summary: TOTAL: 1
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 0
--------------------------------------------------------------------------------------------------

prop name

public prop name: String

功能:获取测试套名称。

类型:String

func runBenchmarks()

public func runBenchmarks(): BenchReport

功能:运行所有性能测试用例。

返回值:

func runBenchmarks(Configuration)

public func runBenchmarks(configuration: Configuration): BenchReport

功能:带配置信息得运行所有性能测试用例。

参数:

返回值:

func runTests()

public func runTests(): TestReport

功能:运行测试套。

返回值:

func runTests(Configuration)

public func runTests(configuration: Configuration): TestReport

功能:带配置信息得运行测试套。

参数:

返回值:

static func builder(String)

public static func builder(name: String): TestSuiteBuilder

功能:创建测试套构建器。

参数:

  • name: String - 测试套名称。

返回值:

static func builder(TestSuite)

public static func builder(suite: TestSuite): TestSuiteBuilder

功能:创建测试套构建器。

参数:

返回值:

class TestSuiteBuilder

public class TestSuiteBuilder {}

功能:提供配置测试套方法的测试套构造器。

请看示例: TestSuite.

func add(Benchmark)

public func add(benchmark: Benchmark): TestSuiteBuilder

功能:为测试套添加性能用例。

参数:

  • benchmark: Benchmark - 性能测试用例。

返回值:

func add(UnitTestCase)

public func add(test: UnitTestCase): TestSuiteBuilder

功能:为测试套添加单元测试用例。

参数:

返回值:

func afterAll(() -> Unit)

public func afterAll(body: () -> Unit): TestSuiteBuilder

功能:为测试套添加在所有用例执行完成后执行的生命周期管理闭包。

参数:

  • body: () -> Unit - 执行体。

返回值:

func afterEach(() -> Unit)

public func afterEach(body: () -> Unit): TestSuiteBuilder

功能:为测试套添加在每个用例执行完成后执行的生命周期管理闭包。

参数:

  • body: () -> Unit - 执行体。

返回值:

func afterEach((String) -> Unit)

public func afterEach(body: (String) -> Unit): TestSuiteBuilder

功能:为测试套添加在每个用例执行完成后执行的生命周期管理闭包。

参数:

  • body: (String) -> Unit - 执行体。

返回值:

func beforeAll(() -> Unit)

public func beforeAll(body: () -> Unit): TestSuiteBuilder

功能:为测试套添加在所有用例执行前执行的生命周期管理闭包。

参数:

  • body: () -> Unit - 执行体。

返回值:

func beforeEach(() -> Unit)

public func beforeEach(body: () -> Unit): TestSuiteBuilder

功能:为测试套添加在每个用例执行前执行的生命周期管理闭包。

参数:

  • body: () -> Unit - 执行体。

返回值:

func beforeEach((String) -> Unit)

public func beforeEach(body: (String) -> Unit): TestSuiteBuilder

功能:为测试套添加在每个用例执行前执行的生命周期管理闭包。

参数:

  • body: (String) -> Unit - 执行体。

返回值:

func template(TestSuite)

public func template(template: TestSuite): TestSuiteBuilder

功能:执行此方法可为测试套件设置模板。

参数

  • template: TestSuite - 将作为模板的测试套件。

返回值:

func build()

public func build(): TestSuite

功能:配置完成后构造测试套。

返回值:

func configure(Configuration)

public func configure(configuration: Configuration): TestSuiteBuilder

功能:为测试套添加配置信息。

参数:

返回值:

func setName(String)

public func setName(name: String): TestSuiteBuilder

功能:为测试套设置名称。

参数:

  • name: String - 测试套名称。

返回值:

class UnitTestCase

public class UnitTestCase {}

功能:提供创建和执行单元测试用例的方法的类。

示例:

import std.unittest.*
import std.unittest.testmacro.*

main() {
    let testCase = UnitTestCase.create("ordinary", body: {
        => @Fail("failing test")
    })

    println("Running ${testCase.name}...")
    testCase.run().reportTo(ConsoleReporter())
    let parametrizedTestCase = UnitTestCase.createParameterized(
        "parametrized",
        [1, 2, 3],
        body: {x => @Assert(1 <= x && x <= 3)}
    )

    println("Running ${parametrizedTestCase.name}...")
    parametrizedTestCase.run().reportTo(ConsoleReporter())
}

可能的运行结果:

Running ordinary...
--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 294492 ns, RESULT:
    TCS: TestCase_ordinary, time elapsed: 289499 ns, RESULT:
    [ FAILED ] CASE: ordinary (35884 ns)
    Assert Failed: `(failing test)`

Summary: TOTAL: 1
    PASSED: 0, SKIPPED: 0, ERROR: 0
    FAILED: 1, listed below:
            TCS: TestCase_ordinary, CASE: ordinary
--------------------------------------------------------------------------------------------------
Running parametrized...
--------------------------------------------------------------------------------------------------
TP: default, time elapsed: 113318 ns, RESULT:
    TCS: TestCase_parametrized, time elapsed: 111489 ns, RESULT:
    [ PASSED ] CASE: parametrized (21603 ns)
Summary: TOTAL: 1
    PASSED: 1, SKIPPED: 0, ERROR: 0
    FAILED: 0
--------------------------------------------------------------------------------------------------

prop name

public prop name: String

功能:获取单元测试名称。

类型:String

func run()

public func run(): TestReport

功能:运行单元测试用例。

返回值:

static func create(String, Configuration, () -> Unit)

public static func create(
    name: String,
    configuration!: Configuration = Configuration(),
    body!: () -> Unit
): UnitTestCase

功能:创建单元测试用例。

参数:

  • name: String - 用例名称。
  • configuration!: Configuration - 用例配置信息。
  • body!: () -> Unit - 用例执行体。

返回值:

static func createParameterized<T>(String, DataStrategy<T>, Configuration, (T) -> Unit)

public static func createParameterized<T>(
    name: String,
    strategy: DataStrategy<T>,
    configuration!: Configuration = Configuration(),
    body!: (T) -> Unit
): UnitTestCase

功能:创建参数化的单元测试用例。

参数:

  • name: String - 用例名称。
  • strategy: DataStrategy - 参数数据策略。
  • configuration!: Configuration - 用例配置信息。
  • body!: () -> Unit - 用例执行体。

返回值:

static func createParameterized<T>(String, DataStrategyProcessor<T>, Configuration, (T) -> Unit)

public static func createParameterized<T>(
    name: String,
    strategy: DataStrategyProcessor<T>,
    configuration!: Configuration = Configuration(),
    body!: (T) -> Unit
): UnitTestCase

功能:创建参数化的单元测试用例。

参数:

返回值:

class XmlReporter

public class XmlReporter <: Reporter<TestReport, Unit> {
    public XmlReporter(let directory: Path)
}

功能:打印单元测试用例结果数据到 Xml 文件上。

父类型:

示例:

import std.fs.*
import std.unittest.*
import std.unittest.testmacro.*

main() {
    let testCase = UnitTestCase.create("testCase", body: {
        => @Fail("failing example")
    })
    let suite1 = TestSuite.builder("suite1").add(testCase).build()
    let suite2 = TestSuite.builder("suite2").build()
    let group = TestGroup.builder("group").add(suite1).add(suite2).build()
    group.runTests().reportTo(XmlReporter(Path(".")))
    let report1 = File.readFrom("./tests/test-group.suite1.xml") |> String.fromUtf8
    let report2 = File.readFrom("./tests/test-group.suite2.xml") |> String.fromUtf8
    println(report1)
    println(report2)
}

可能的运行结果:

<?xml version="1.0" encoding="UTF-8"?>
<>
        <testsuite name="group.suite1" tests="1" failures="1" errors="0" skipped="0" time="0.000350" timestamp="2025-12-30T16:27:15.005019525+03:00">
                <testcase name="testCase" classname="group.suite1" assertions="1" time="0.000045">
                        <failure>Assert Failed: `(failing example)`</failure>
                </testcase>
        </testsuite>
</>

<?xml version="1.0" encoding="UTF-8"?>
<>
        <testsuite name="group.suite2" tests="0" failures="0" errors="0" skipped="0" time="0.000000" timestamp="2025-12-30T16:27:15.00537593+03:00"/>
</>

XmlReporter(Path)

public XmlReporter(let directory: Path)

功能:XmlReporter 构造函数。

参数:

  • directory: Path - 打印文件生成地址。

class XmlPerPackageReporter

public class XmlPerPackageReporter <: Reporter<TestReport, Unit> {
    public XmlPerPackageReporter(let directory: Path)
}

功能:打印单元测试用例结果数据到 Xml 文件上。

父类型:

示例:

import std.fs.*
import std.unittest.*
import std.unittest.testmacro.*

main() {
    let testCase = UnitTestCase.create("testCase", body: {
        => @Fail("failing example")
    })
    let suite1 = TestSuite.builder("suite1").add(testCase).build()
    let suite2 = TestSuite.builder("suite2").build()
    let group = TestGroup.builder("group").add(suite1).add(suite2).build()
    group.runTests().reportTo(XmlPerPackageReporter(Path(".")))
    let report = File.readFrom("./tests/test-group.xml") |> String.fromUtf8
    println(report)
}

可能的运行结果:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="group" tests="1" failures="1" errors="0" skipped="0" time="0.000288" timestamp="2025-12-30T16:28:16.852259739+03:00">
        <testsuite name="group.suite1" tests="1" failures="1" errors="0" skipped="0" time="0.000280" timestamp="2025-12-30T16:28:16.852264581+03:00">
                <testcase name="testCase" classname="group.suite1" assertions="1" time="0.000046">
                        <failure>Assert Failed: `(failing example)`</failure>
                </testcase>
        </testsuite>
        <testsuite name="group.suite2" tests="0" failures="0" errors="0" skipped="0" time="0.000000" timestamp="2025-12-30T16:28:16.852547919+03:00"/>
</testsuites>

XmlPerPackageReporter(Path)

public XmlReporter(let directory: Path)

功能:XmlPerPackageReporter 构造函数。

参数:

  • directory: Path - 打印文件生成地址。