add TestSchema module (#591)

This commit is contained in:
Giulio Canti
2025-09-29 08:53:14 +02:00
committed by GitHub
parent 15abfd0f83
commit 0eca3db4ca
21 changed files with 3731 additions and 2855 deletions
+1 -3
View File
@@ -4148,9 +4148,7 @@ const schema = Schema.String.pipe(
// ┌─── Codec<string, string, never, never>
// ▼
const provided = schema.pipe(
Schema.decodingMiddleware((sr) =>
Effect.isEffect(sr) ? Effect.provideService(sr, Service, { fallback: Effect.succeed("b") }) : sr
)
Schema.decodingMiddleware(Effect.provideService(Service, { fallback: Effect.succeed("b") }))
)
console.log(String(Schema.decodeUnknownExit(provided)(null)))
+7 -14
View File
@@ -259,9 +259,6 @@ export interface ParseOptions {
* default: "none"
*/
readonly propertyOrder?: "none" | "original" | undefined
/** @internal */
readonly "~variant"?: "make" | undefined
}
/** @internal */
@@ -276,8 +273,6 @@ export class Context {
readonly isMutable: boolean
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
readonly defaultValue: Encoding | undefined
/** Used for constructor encoding (e.g. `Class` API) */
readonly make: Encoding | undefined
readonly annotations: Annotations.Key<unknown> | undefined
constructor(
@@ -285,14 +280,11 @@ export class Context {
isMutable: boolean,
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
defaultValue: Encoding | undefined = undefined,
/** Used for constructor encoding (e.g. `Class` API) */
make: Encoding | undefined = undefined,
annotations: Annotations.Key<unknown> | undefined = undefined
) {
this.isOptional = isOptional
this.isMutable = isMutable
this.defaultValue = defaultValue
this.make = make
this.annotations = annotations
}
}
@@ -1991,17 +1983,16 @@ export function annotateKey<A extends AST>(ast: A, annotations: Annotations.Key<
ast.context.isOptional,
ast.context.isMutable,
ast.context.defaultValue,
ast.context.make,
Annotations.combine(ast.context.annotations, annotations)
) :
new Context(false, false, undefined, undefined, annotations)
new Context(false, false, undefined, annotations)
return replaceContext(ast, context)
}
/** @internal */
export function optionalKey<A extends AST>(ast: A): A {
const context = ast.context ?
new Context(true, ast.context.isMutable, ast.context.defaultValue, ast.context.make, ast.context.annotations) :
new Context(true, ast.context.isMutable, ast.context.defaultValue, ast.context.annotations) :
new Context(true, false)
return applyEncoded(replaceContext(ast, context), optionalKey)
}
@@ -2009,7 +2000,7 @@ export function optionalKey<A extends AST>(ast: A): A {
/** @internal */
export function mutableKey<A extends AST>(ast: A): A {
const context = ast.context ?
new Context(ast.context.isOptional, true, ast.context.defaultValue, ast.context.make, ast.context.annotations) :
new Context(ast.context.isOptional, true, ast.context.defaultValue, ast.context.annotations) :
new Context(false, true)
return applyEncoded(replaceContext(ast, context), mutableKey)
}
@@ -2032,7 +2023,7 @@ export function withConstructorDefault<A extends AST>(
)
const encoding: Encoding = [new Link(unknownKeyword, transformation)]
const context = ast.context ?
new Context(ast.context.isOptional, ast.context.isMutable, encoding, ast.context.make, ast.context.annotations) :
new Context(ast.context.isOptional, ast.context.isMutable, encoding, ast.context.annotations) :
new Context(false, false, encoding)
return replaceContext(ast, context)
}
@@ -2063,7 +2054,6 @@ function mutableContext(ast: AST, isMutable: boolean): AST {
ast.context.isOptional,
isMutable,
ast.context.defaultValue,
ast.context.make,
ast.context.annotations
)
: new Context(false, isMutable)
@@ -2535,3 +2525,6 @@ export function runChecks<T>(
export function runRefine<T extends E, E>(refine: Check.Refine<T, E>, s: E): Result.Result<T, Issue.Issue> {
return runChecks([refine], s) as any
}
/** @internal */
export const ClassTypeId = "~effect/schema/Schema/Class"
+30 -12
View File
@@ -2467,14 +2467,15 @@ export interface decodingMiddleware<S extends Top, RD> extends
*/
export function decodingMiddleware<S extends Top, RD>(
decode: (
sr: Effect.Effect<Option_.Option<S["Type"]>, Issue.Issue, S["DecodingServices"]>,
effect: Effect.Effect<Option_.Option<S["Type"]>, Issue.Issue, S["DecodingServices"]>,
options: AST.ParseOptions
) => Effect.Effect<Option_.Option<S["Type"]>, Issue.Issue, RD>
) {
return (schema: S): decodingMiddleware<S, RD> => {
return makeProto(AST.decodingMiddleware(schema.ast, new Transformation.Middleware(decode, identity)), {
schema
})
return makeProto(
AST.decodingMiddleware(schema.ast, new Transformation.Middleware(decode, identity)),
{ schema }
)
}
}
@@ -2514,7 +2515,10 @@ export function encodingMiddleware<S extends Top, RE>(
) => Effect.Effect<Option_.Option<S["Type"]>, Issue.Issue, RE>
) {
return (schema: S): encodingMiddleware<S, RE> => {
return makeProto(AST.encodingMiddleware(schema.ast, new Transformation.Middleware(identity, encode)), { schema })
return makeProto(
AST.encodingMiddleware(schema.ast, new Transformation.Middleware(identity, encode)),
{ schema }
)
}
}
@@ -2656,7 +2660,9 @@ export function encodeTo<To extends Top, From extends Top, RD = never, RE = neve
}
) {
return (from: From): decodeTo<From, To, RD, RE> => {
return transformation ? to.pipe(decodeTo(from, transformation)) : to.pipe(decodeTo(from))
return transformation ?
to.pipe(decodeTo(from, transformation)) :
to.pipe(decodeTo(from))
}
}
@@ -2716,7 +2722,10 @@ export function withConstructorDefault<S extends Top & WithoutConstructorDefault
) => Option_.Option<S["~type.make.in"]> | Effect.Effect<Option_.Option<S["~type.make.in"]>>
) {
return (schema: S): withConstructorDefault<S> => {
return makeProto(AST.withConstructorDefault(schema.ast, defaultValue), { schema })
return makeProto(
AST.withConstructorDefault(schema.ast, defaultValue),
{ schema }
)
}
}
@@ -3590,7 +3599,11 @@ export const Error: Error = instanceOf(globalThis.Error, {
link<globalThis.Error>()(
ErrorJsonEncoded,
Transformation.error()
)
),
arbitrary: {
_tag: "Declaration",
declaration: () => (fc) => fc.string().map((message) => new globalThis.Error(message))
}
})
/**
@@ -4438,6 +4451,7 @@ function getClassSchemaFactory<S extends Top>(
self: Self
): decodeTo<declareConstructor<Self, S["Encoded"], readonly [S]>, S> => {
if (memo === undefined) {
const transformation = getClassTransformation(self)
const to = make<declareConstructor<Self, S["Encoded"], readonly [S]>>(
new AST.Declaration(
[from.ast],
@@ -4447,8 +4461,8 @@ function getClassSchemaFactory<S extends Top>(
Effect.fail(new Issue.InvalidType(ast, Option_.some(input)))
},
Annotations.combine({
defaultIsoSerializer: ([from]: readonly [Schema<S["Type"]>]) =>
new AST.Link(from.ast, getClassTransformation(self)),
[AST.ClassTypeId]: ([from]: readonly [AST.AST]) => new AST.Link(from, transformation),
defaultIsoSerializer: ([from]: readonly [Schema<S["Type"]>]) => new AST.Link(from.ast, transformation),
arbitrary: {
_tag: "Declaration",
declaration: ([from]: readonly [FastCheck.Arbitrary<S["Type"]>]) => () =>
@@ -4576,7 +4590,7 @@ export const RequestClass =
/**
* @since 4.0.0
*/
export const PropertyKey = Union([Symbol, String, Finite])
export const PropertyKey = Union([Finite, Symbol, String])
/**
* @since 4.0.0
@@ -4630,7 +4644,11 @@ export const Uint8Array: Uint8Array = instanceOf(globalThis.Uint8Array<ArrayBuff
decode: Getter.decodeBase64(),
encode: Getter.encodeBase64()
}
)
),
arbitrary: {
_tag: "Declaration",
declaration: () => (fc) => fc.uint8Array()
}
})
/**
+32 -13
View File
@@ -6,6 +6,7 @@ import * as Cause from "../Cause.ts"
import * as Arr from "../collections/Array.ts"
import * as Filter from "../data/Filter.ts"
import * as Option from "../data/Option.ts"
import * as Predicate from "../data/Predicate.ts"
import * as Effect from "../Effect.ts"
import * as Exit from "../Exit.ts"
import { memoize } from "../Function.ts"
@@ -14,15 +15,42 @@ import * as AST from "./AST.ts"
import * as Issue from "./Issue.ts"
import type * as Schema from "./Schema.ts"
const goDefaults = memoize((ast: AST.AST): AST.AST => {
switch (ast._tag) {
case "Declaration": {
const getLink = ast.annotations?.[AST.ClassTypeId]
if (Predicate.isFunction(getLink)) {
const link = getLink(ast.typeParameters)
const to = goDefaults(link.to)
return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)])
}
return ast
}
case "TypeLiteral":
case "TupleType":
return ast.go((ast) => {
const defaultValue = ast.context?.defaultValue
if (defaultValue) {
return AST.replaceEncoding(goDefaults(ast), defaultValue)
}
return goDefaults(ast)
})
case "Suspend":
return ast.go(goDefaults)
default:
return ast
}
})
/**
* @category Constructing
* @since 4.0.0
*/
export function makeEffect<S extends Schema.Top>(schema: S) {
const parser = run<S["Type"], never>(AST.typeAST(schema.ast))
const ast = goDefaults(AST.typeAST(schema.ast))
const parser = run<S["Type"], never>(ast)
return (input: S["~type.make.in"], options?: Schema.MakeOptions): Effect.Effect<S["Type"], Issue.Issue> => {
const parseOptions: AST.ParseOptions = { "~variant": "make", ...options?.parseOptions }
return parser(input, parseOptions)
return parser(input, options?.parseOptions)
}
}
@@ -319,16 +347,7 @@ const go = memoize(
const isStructural = AST.isTupleType(ast) || AST.isTypeLiteral(ast) ||
(AST.isDeclaration(ast) && ast.typeParameters.length > 0)
return (ou, options) => {
let encoding = ast.encoding
if (options["~variant"] === "make" && ast.context) {
if (ast.context.defaultValue) {
encoding = ast.context.defaultValue
}
if (ast.context.make) {
encoding = encoding ? [...encoding, ...ast.context.make] : ast.context.make
}
}
const encoding = ast.encoding
let srou: Effect.Effect<Option.Option<unknown>, Issue.Issue, unknown> | undefined
if (encoding) {
const links = encoding
+288
View File
@@ -0,0 +1,288 @@
/**
* Testing utilities for Schema validation and assertions.
*
* @since 4.0.0
*/
import * as assert from "node:assert"
import * as Record from "../data/Record.ts"
import * as Result from "../data/Result.ts"
import * as Effect from "../Effect.ts"
import * as AST from "../schema/AST.ts"
import type * as Issue from "../schema/Issue.ts"
import * as Schema from "../schema/Schema.ts"
import * as ToArbitrary from "../schema/ToArbitrary.ts"
import * as ToParser from "../schema/ToParser.ts"
import type * as ServiceMap from "../ServiceMap.ts"
import * as FastCheck from "../testing/FastCheck.ts"
/**
* The `Asserts` class provides a comprehensive testing framework for schema validation,
* encoding/decoding operations, and property-based testing.
*
* @since 4.0.0
*/
export class Asserts<S extends Schema.Top> {
static ast = {
/** Asserts that two struct field definitions are equal by comparing their AST representations. */
fields: {
equals: (a: Schema.Struct.Fields, b: Schema.Struct.Fields) => {
assert.deepStrictEqual(Record.map(a, AST.getAST), Record.map(b, AST.getAST))
}
},
/** Asserts that two tuple element definitions are equal by comparing their AST representations. */
elements: {
equals: (a: Schema.Tuple.Elements, b: Schema.Tuple.Elements) => {
assert.deepStrictEqual(a.map(AST.getAST), b.map(AST.getAST))
}
}
} as const
readonly schema: S
constructor(schema: S) {
this.schema = schema
}
/**
* Provides make operation testing utilities.
*/
make(options?: Schema.MakeOptions) {
const makeEffect = ToParser.makeEffect(this.schema)
async function succeed(input: S["Type"]): Promise<void>
async function succeed(input: S["~type.make.in"], expected: S["Type"]): Promise<void>
async function succeed(input: S["~type.make.in"], expected?: S["Type"]) {
const r = await Effect.runPromise(
makeEffect(input, options).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
expected = arguments.length === 1 ? input : expected
assert.deepStrictEqual(r, Result.succeed(expected))
}
return {
succeed,
/**
* Asserts that make operation fails with the expected error message.
*/
async fail(input: unknown, message: string) {
const r = await Effect.runPromise(
makeEffect(input, options).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
assert.deepStrictEqual(r, Result.fail(message))
}
}
}
/**
* Verifies that encoding values produces the same type after decoding (round-trip).
*/
verifyLosslessTransformation<S extends Schema.Codec<unknown, unknown>>(this: Asserts<S>, options?: {
readonly params?: FastCheck.Parameters<[S["Type"]]>
}) {
const decodeUnknownEffect = ToParser.decodeUnknownEffect(this.schema)
const encodeEffect = ToParser.encodeEffect(this.schema)
const arbitrary = ToArbitrary.make(this.schema)
return FastCheck.assert(
FastCheck.asyncProperty(arbitrary, async (t) => {
const r = await Effect.runPromise(
encodeEffect(t).pipe(
Effect.flatMap((e) => decodeUnknownEffect(e)),
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
assert.deepStrictEqual(r, Result.succeed(t))
}),
options?.params
)
}
/**
* Provides decoding testing utilities.
*/
decoding(options?: {
readonly parseOptions?: AST.ParseOptions | undefined
}) {
return new Decoding(this.schema, options)
}
/**
* Provides encoding testing utilities.
*/
encoding(options?: {
readonly parseOptions?: AST.ParseOptions | undefined
}) {
return new Encoding(this.schema, options)
}
/**
* Provides property-based testing utilities for schema validation.
*/
arbitrary<S extends Schema.Codec<unknown, unknown, never, unknown>>(this: Asserts<S>) {
const schema = this.schema
return {
/**
* Verifies that the schema generates valid arbitrary values that satisfy
* the schema constraints.
*/
verifyGeneration(options?: {
readonly params?: FastCheck.Parameters<[S["Type"]]> | undefined
}) {
const params = options?.params
const is = Schema.is(schema)
const arb = ToArbitrary.make(schema)
FastCheck.assert(FastCheck.property(arb, (a) => is(a)), { numRuns: 20, ...params })
}
}
}
}
/**
* @since 4.0.0
*/
export class Decoding<S extends Schema.Top> {
readonly schema: S
readonly decodeUnknownEffect: (
input: unknown,
options?: AST.ParseOptions
) => Effect.Effect<S["Type"], Issue.Issue, S["DecodingServices"]>
readonly options?: {
readonly parseOptions?: AST.ParseOptions | undefined
} | undefined
constructor(schema: S, options?: {
readonly parseOptions?: AST.ParseOptions | undefined
}) {
this.schema = schema
this.decodeUnknownEffect = ToParser.decodeUnknownEffect(schema)
this.options = options
}
/**
* Asserts that decoding succeeds with the expected value.
*/
async succeed<S extends Schema.Codec<unknown, unknown, never, unknown>>(
this: Decoding<S>,
input: unknown
): Promise<void>
async succeed<S extends Schema.Codec<unknown, unknown, never, unknown>>(
this: Decoding<S>,
input: unknown,
expected: S["Type"]
): Promise<void>
async succeed<S extends Schema.Codec<unknown, unknown, never, unknown>>(
this: Decoding<S>,
input: unknown,
expected?: S["Type"]
) {
const r = await Effect.runPromise(
this.decodeUnknownEffect(input, this.options?.parseOptions).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
expected = arguments.length === 1 ? input : expected
assert.deepStrictEqual(r, Result.succeed(expected))
}
/**
* Asserts that decoding fails with the expected error message.
*/
async fail<S extends Schema.Codec<unknown, unknown, never, unknown>>(
this: Decoding<S>,
input: unknown,
message: string
) {
const r = await Effect.runPromise(
this.decodeUnknownEffect(input, this.options?.parseOptions).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
assert.deepStrictEqual(r, Result.fail(message))
}
/**
* Creates a new Decoding instance with the provided service available in the
* decoding context.
*/
provide<Id, Service>(
key: ServiceMap.Key<Id, Service>,
service: Service
): Decoding<Schema.decodingMiddleware<S, Exclude<S["DecodingServices"], Id>>> {
return new Decoding(
this.schema.pipe(Schema.decodingMiddleware(Effect.provideService(key, service))),
this.options
)
}
}
/**
* @since 4.0.0
*/
class Encoding<S extends Schema.Top> {
readonly schema: S
readonly encodeUnknownEffect: (
input: unknown,
options?: AST.ParseOptions
) => Effect.Effect<S["Type"], Issue.Issue, S["EncodingServices"]>
readonly options?: {
readonly parseOptions?: AST.ParseOptions | undefined
} | undefined
constructor(schema: S, options?: {
readonly parseOptions?: AST.ParseOptions | undefined
}) {
this.schema = schema
this.encodeUnknownEffect = ToParser.encodeUnknownEffect(schema)
this.options = options
}
/**
* Asserts that encoding succeeds with the expected value.
*/
async succeed<S extends Schema.Codec<unknown, unknown, unknown, never>>(
this: Encoding<S>,
input: unknown
): Promise<void>
async succeed<S extends Schema.Codec<unknown, unknown, unknown, never>>(
this: Encoding<S>,
input: unknown,
expected: S["Encoded"]
): Promise<void>
async succeed<S extends Schema.Codec<unknown, unknown, unknown, never>>(
this: Encoding<S>,
input: unknown,
expected?: S["Encoded"]
) {
const r = await Effect.runPromise(
this.encodeUnknownEffect(input, this.options?.parseOptions).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
expected = arguments.length === 1 ? input : expected
assert.deepStrictEqual(r, Result.succeed(expected))
}
/**
* Asserts that encoding fails with the expected error message.
*/
async fail<S extends Schema.Codec<unknown, unknown, unknown, never>>(
this: Encoding<S>,
input: unknown,
message: string
) {
const r = await Effect.runPromise(
this.encodeUnknownEffect(input, this.options?.parseOptions).pipe(
Effect.mapError((issue) => issue.toString()),
Effect.result
)
)
assert.deepStrictEqual(r, Result.fail(message))
}
/**
* Creates a new Encoding instance with the provided service available in the
* encoding context.
*/
provide<Id, Service>(
key: ServiceMap.Key<Id, Service>,
service: Service
): Encoding<Schema.encodingMiddleware<S, Exclude<S["EncodingServices"], Id>>> {
return new Encoding(
this.schema.pipe(Schema.encodingMiddleware(Effect.provideService(key, service))),
this.options
)
}
}
+5
View File
@@ -24,3 +24,8 @@ export * as TestClock from "./TestClock.ts"
* @since 4.0.0
*/
export * as TestConsole from "./TestConsole.ts"
/**
* @since 4.0.0
*/
export * as TestSchema from "./TestSchema.ts"
+163 -157
View File
@@ -1,26 +1,32 @@
import { describe, it } from "@effect/vitest"
import { deepStrictEqual } from "@effect/vitest/utils"
import { Config, ConfigProvider, Duration, Effect, pipe } from "effect"
import { Option, Redacted } from "effect/data"
import { Option, Redacted, Result } from "effect/data"
import { Issue, Schema } from "effect/schema"
import { assertions } from "../utils/schema.ts"
import * as assert from "node:assert"
async function assertSuccess<T>(config: Config.Config<T>, provider: ConfigProvider.ConfigProvider, expected: T) {
const result = config.parse(provider)
return await assertions.effect.succeed(result, expected)
async function succeed<T>(config: Config.Config<T>, provider: ConfigProvider.ConfigProvider, expected: T) {
const r = await config.parse(provider).pipe(
Effect.result,
Effect.runPromise
)
assert.deepStrictEqual(r, Result.succeed(expected))
}
async function assertFailure<T>(config: Config.Config<T>, provider: ConfigProvider.ConfigProvider, message: string) {
const result = config.parse(provider).pipe(
async function fail<T>(config: Config.Config<T>, provider: ConfigProvider.ConfigProvider, message: string) {
const r = await config.parse(provider).pipe(
Effect.catchTag(
"SourceError",
(e) =>
Effect.fail(
new Schema.SchemaError(new Issue.InvalidValue(Option.none(), { message: `SourceError: ${e.message}` }))
)
)
),
Effect.mapError((e) => e.issue.toString()),
Effect.result,
Effect.runPromise
)
return await assertions.effect.fail(result.pipe(Effect.mapError((e) => e.issue)), message)
assert.deepStrictEqual(r, Result.fail(message))
}
describe("Config", () => {
@@ -36,12 +42,12 @@ describe("Config", () => {
it("map", async () => {
const config = Config.schema(Schema.String)
await assertSuccess(
await succeed(
Config.map(config, (value) => value.toUpperCase()),
ConfigProvider.fromStringPojo("value"),
"VALUE"
)
await assertSuccess(
await succeed(
pipe(config, Config.map((value) => value.toUpperCase())),
ConfigProvider.fromStringPojo("value"),
"VALUE"
@@ -55,12 +61,12 @@ describe("Config", () => {
? Effect.fail(new Schema.SchemaError(new Issue.InvalidValue(Option.some(s), { message: "empty" })))
: Effect.succeed(s.toUpperCase())
await assertSuccess(
await succeed(
Config.mapOrFail(config, f),
ConfigProvider.fromStringPojo("value"),
"VALUE"
)
await assertFailure(
await fail(
Config.mapOrFail(config, f),
ConfigProvider.fromStringPojo(""),
`empty`
@@ -70,12 +76,12 @@ describe("Config", () => {
it("orElse", async () => {
const config = Config.orElse(Config.string("a"), () => Config.finite("b"))
await assertSuccess(
await succeed(
config,
ConfigProvider.fromStringPojo({ a: "value" }),
"value"
)
await assertSuccess(
await succeed(
config,
ConfigProvider.fromStringPojo({ b: "1" }),
1
@@ -86,14 +92,14 @@ describe("Config", () => {
it("tuple", async () => {
const config = Config.all([Config.nonEmptyString("a"), Config.finite("b")])
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "a", b: "1" }), ["a", 1])
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "a", b: "1" }), ["a", 1])
await fail(
config,
ConfigProvider.fromStringPojo({ a: "", b: "1" }),
`Expected a value with a length of at least 1, got ""
at ["a"]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ a: "a", b: "b" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "b"
@@ -104,14 +110,14 @@ describe("Config", () => {
it("iterable", async () => {
const config = Config.all(new Set([Config.nonEmptyString("a"), Config.finite("b")]))
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "a", b: "1" }), ["a", 1])
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "a", b: "1" }), ["a", 1])
await fail(
config,
ConfigProvider.fromStringPojo({ a: "", b: "1" }),
`Expected a value with a length of at least 1, got ""
at ["a"]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ a: "a", b: "b" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "b"
@@ -122,14 +128,14 @@ describe("Config", () => {
it("struct", async () => {
const config = Config.all({ a: Config.nonEmptyString("b"), c: Config.finite("d") })
await assertSuccess(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), { a: "b", c: 1 })
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), { a: "b", c: 1 })
await fail(
config,
ConfigProvider.fromStringPojo({ b: "", d: "1" }),
`Expected a value with a length of at least 1, got ""
at ["b"]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ b: "b", d: "b" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "b"
@@ -143,9 +149,9 @@ describe("Config", () => {
const defaultValue = 0
const config = Config.finite("a").pipe(Config.withDefault(() => defaultValue))
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), 1)
await assertSuccess(config, ConfigProvider.fromStringPojo({}), defaultValue)
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), 1)
await succeed(config, ConfigProvider.fromStringPojo({}), defaultValue)
await fail(
config,
ConfigProvider.fromStringPojo({ a: "value" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -159,11 +165,11 @@ describe("Config", () => {
Config.withDefault(() => defaultValue)
)
await assertSuccess(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), { a: "b", c: 1 })
await assertSuccess(config, ConfigProvider.fromStringPojo({ b: "b" }), defaultValue)
await assertSuccess(config, ConfigProvider.fromStringPojo({ d: "1" }), defaultValue)
await succeed(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), { a: "b", c: 1 })
await succeed(config, ConfigProvider.fromStringPojo({ b: "b" }), defaultValue)
await succeed(config, ConfigProvider.fromStringPojo({ d: "1" }), defaultValue)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ b: "", d: "1" }),
`Expected a value with a length of at least 1, got ""
@@ -176,9 +182,9 @@ describe("Config", () => {
it("value", async () => {
const config = Config.finite("a").pipe(Config.option)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), Option.some(1))
await assertSuccess(config, ConfigProvider.fromStringPojo({}), Option.none())
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), Option.some(1))
await succeed(config, ConfigProvider.fromStringPojo({}), Option.none())
await fail(
config,
ConfigProvider.fromStringPojo({ a: "value" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -191,11 +197,11 @@ describe("Config", () => {
Config.option
)
await assertSuccess(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), Option.some({ a: "b", c: 1 }))
await assertSuccess(config, ConfigProvider.fromStringPojo({ b: "b" }), Option.none())
await assertSuccess(config, ConfigProvider.fromStringPojo({ d: "1" }), Option.none())
await succeed(config, ConfigProvider.fromStringPojo({ b: "b", d: "1" }), Option.some({ a: "b", c: 1 }))
await succeed(config, ConfigProvider.fromStringPojo({ b: "b" }), Option.none())
await succeed(config, ConfigProvider.fromStringPojo({ d: "1" }), Option.none())
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ b: "", d: "1" }),
`Expected a value with a length of at least 1, got ""
@@ -210,7 +216,7 @@ describe("Config", () => {
a: Config.schema(Schema.String, "a2")
})
await assertSuccess(config, ConfigProvider.fromStringPojo({ a2: "value" }), { a: "value" })
await succeed(config, ConfigProvider.fromStringPojo({ a2: "value" }), { a: "value" })
})
it("nested", async () => {
@@ -220,7 +226,7 @@ describe("Config", () => {
}
})
await assertSuccess(
await succeed(
config,
ConfigProvider.fromStringPojo({ b2: "value" }),
{ a: { b: "value" } }
@@ -234,43 +240,43 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Finite })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1", "a__b": "2" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1", "a__b": "2" } }), { a: 1 })
})
it("node can be both leaf and array", async () => {
const schema = Schema.Struct({ a: Schema.Finite })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1", "a__0": "2" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1", "a__0": "2" } }), { a: 1 })
})
it("if a node can be both object and array, it should be an object", async () => {
const schema = Schema.Struct({ a: Schema.Struct({ b: Schema.Finite }) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1", "a__b": "2", "a__0": "3" } }), {
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1", "a__b": "2", "a__0": "3" } }), {
a: { b: 2 }
})
})
})
it("path argument", async () => {
await assertSuccess(
await succeed(
Config.schema(Schema.String, "a"),
ConfigProvider.fromEnv({ env: { a: "value" } }),
"value"
)
await assertSuccess(
await succeed(
Config.schema(Schema.String, ["a", "b"]),
ConfigProvider.fromEnv({ env: { "a__b": "value" } }),
"value"
)
await assertSuccess(
await succeed(
Config.schema(Schema.UndefinedOr(Schema.String)),
ConfigProvider.fromEnv({ env: {} }),
undefined
)
await assertSuccess(
await succeed(
Config.schema(Schema.UndefinedOr(Schema.String), "a"),
ConfigProvider.fromEnv({ env: {} }),
undefined
@@ -281,8 +287,8 @@ describe("Config", () => {
const schema = Schema.String
const config = Config.schema(schema, "a")
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "a" } }), "a")
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "a" } }), "a")
await fail(
config,
ConfigProvider.fromEnv({ env: {} }),
`Expected string, got undefined
@@ -295,15 +301,15 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Finite })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
})
it("optionalKey properties", async () => {
const schema = Schema.Struct({ a: Schema.optionalKey(Schema.Finite) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromEnv({ env: {} }), {})
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: {} }), {})
})
it("optional properties", async () => {
@@ -311,25 +317,25 @@ describe("Config", () => {
Schema.Struct({ a: Schema.optional(Schema.Finite) })
)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromEnv({ env: {} }), {})
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: {} }), {})
})
it("Literals", async () => {
const schema = Schema.Struct({ a: Schema.Literals(["b", "c"]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "b" } }), { a: "b" })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "c" } }), { a: "c" })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "b" } }), { a: "b" })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "c" } }), { a: "c" })
})
it("Array(Finite)", async () => {
const schema = Schema.Struct({ a: Schema.Array(Schema.Finite) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "" } }), { a: [] })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a__0: "1", a__1: "2" } }), { a: [1, 2] })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "" } }), { a: [] })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
await succeed(config, ConfigProvider.fromEnv({ env: { a__0: "1", a__1: "2" } }), { a: [1, 2] })
})
})
@@ -338,9 +344,9 @@ describe("Config", () => {
const schema = Schema.Record(Schema.String, Schema.Finite)
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1", b: "2" } }), { a: 1, b: 2 })
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1", b: "2" } }), { a: 1, b: 2 })
await fail(
config,
ConfigProvider.fromEnv({ env: { a: "1", b: "value" } }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -354,28 +360,28 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Tuple([]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "" } }), { a: [] })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "" } }), { a: [] })
})
it("ensure array", async () => {
const schema = Schema.Struct({ a: Schema.Tuple([Schema.Finite]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
})
it("required elements", async () => {
const schema = Schema.Struct({ a: Schema.Tuple([Schema.String, Schema.Finite]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a__0: "a", a__1: "2" } }), { a: ["a", 2] })
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a__0: "a", a__1: "2" } }), { a: ["a", 2] })
await fail(
config,
ConfigProvider.fromEnv({ env: { a: "a" } }),
`Missing key
at ["a"][1]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromEnv({ env: { a__0: "a", a__1: "value" } }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -388,9 +394,9 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Array(Schema.Finite) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a__0: "1", a__1: "2" } }), { a: [1, 2] })
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), { a: [1] })
await succeed(config, ConfigProvider.fromEnv({ env: { a__0: "1", a__1: "2" } }), { a: [1, 2] })
await fail(
config,
ConfigProvider.fromEnv({ env: { a__0: "1", a__1: "value" } }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -404,8 +410,8 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Literals(["a", "b"]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "b" } }), { a: "b" })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "b" } }), { a: "b" })
})
})
@@ -416,9 +422,9 @@ describe("Config", () => {
])
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { b: "1" } }), { b: 1 })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "a", b: "1" } }), { a: "a" })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await succeed(config, ConfigProvider.fromEnv({ env: { b: "1" } }), { b: 1 })
await succeed(config, ConfigProvider.fromEnv({ env: { a: "a", b: "1" } }), { a: "a" })
})
it("exclusive", async () => {
@@ -428,9 +434,9 @@ describe("Config", () => {
], { mode: "oneOf" })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await assertSuccess(config, ConfigProvider.fromEnv({ env: { b: "1" } }), { b: 1 })
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "a" } }), { a: "a" })
await succeed(config, ConfigProvider.fromEnv({ env: { b: "1" } }), { b: 1 })
await fail(
config,
ConfigProvider.fromEnv({ env: { a: "a", b: "1" } }),
`Expected exactly one member to match the input {"a":"a","b":"1"}`
@@ -449,8 +455,8 @@ describe("Config", () => {
})
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1", as: "" } }), { a: "1", as: [] })
await assertSuccess(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1", as: "" } }), { a: "1", as: [] })
await succeed(
config,
ConfigProvider.fromEnv({ env: { a: "1", as__0__a: "2", as__0__as__TYPE: "A" } }),
{
@@ -464,14 +470,14 @@ describe("Config", () => {
const schema = Schema.Redacted(Schema.Int)
const config = Config.schema(schema, "a")
await assertSuccess(config, ConfigProvider.fromEnv({ env: { a: "1" } }), Redacted.make(1))
await assertFailure(
await succeed(config, ConfigProvider.fromEnv({ env: { a: "1" } }), Redacted.make(1))
await fail(
config,
ConfigProvider.fromEnv({ env: {} }),
`Expected string, got undefined
at ["a"]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromEnv({ env: { a: "1.1" } }),
`Expected an integer, got 1.1
@@ -482,17 +488,17 @@ describe("Config", () => {
describe("fromStringLeafJson", () => {
it("path argument", async () => {
await assertSuccess(
await succeed(
Config.schema(Schema.String, []),
ConfigProvider.fromStringPojo("value"),
"value"
)
await assertSuccess(
await succeed(
Config.schema(Schema.String, "a"),
ConfigProvider.fromStringPojo({ a: "value" }),
"value"
)
await assertSuccess(
await succeed(
Config.schema(Schema.String, ["a", "b"]),
ConfigProvider.fromStringPojo({ a: { b: "value" } }),
"value"
@@ -503,8 +509,8 @@ describe("Config", () => {
const schema = Schema.String
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo("value"), "value")
await assertFailure(config, ConfigProvider.fromStringPojo({}), `Expected string, got undefined`)
await succeed(config, ConfigProvider.fromStringPojo("value"), "value")
await fail(config, ConfigProvider.fromStringPojo({}), `Expected string, got undefined`)
})
describe("Struct", () => {
@@ -512,14 +518,14 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.Finite })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await fail(
config,
ConfigProvider.fromStringPojo({}),
`Missing key
at ["a"]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo({ a: "value" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -531,8 +537,8 @@ describe("Config", () => {
const schema = Schema.Struct({ a: Schema.optionalKey(Schema.Finite) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromStringPojo({}), {})
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await succeed(config, ConfigProvider.fromStringPojo({}), {})
})
it("optional properties", async () => {
@@ -540,16 +546,16 @@ describe("Config", () => {
Schema.Struct({ a: Schema.optional(Schema.Finite) })
)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromStringPojo({}), {})
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await succeed(config, ConfigProvider.fromStringPojo({}), {})
})
it("Literals", async () => {
const schema = Schema.Struct({ a: Schema.Literals(["b", "c"]) })
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "b" }), { a: "b" })
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "c" }), { a: "c" })
await succeed(config, ConfigProvider.fromStringPojo({ a: "b" }), { a: "b" })
await succeed(config, ConfigProvider.fromStringPojo({ a: "c" }), { a: "c" })
})
})
@@ -557,9 +563,9 @@ describe("Config", () => {
const schema = Schema.Record(Schema.String, Schema.Finite)
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1", b: "2" }), { a: 1, b: 2 })
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo({ a: "1" }), { a: 1 })
await succeed(config, ConfigProvider.fromStringPojo({ a: "1", b: "2" }), { a: 1, b: 2 })
await fail(
config,
ConfigProvider.fromStringPojo({ a: "1", b: "value" }),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -572,22 +578,22 @@ describe("Config", () => {
const schema = Schema.Tuple([Schema.Finite])
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo(["1"]), [1])
await assertSuccess(config, ConfigProvider.fromStringPojo("1"), [1])
await succeed(config, ConfigProvider.fromStringPojo(["1"]), [1])
await succeed(config, ConfigProvider.fromStringPojo("1"), [1])
})
it("required elements", async () => {
const schema = Schema.Tuple([Schema.String, Schema.Finite])
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo(["a", "2"]), ["a", 2])
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo(["a", "2"]), ["a", 2])
await fail(
config,
ConfigProvider.fromStringPojo(["a"]),
`Missing key
at [1]`
)
await assertFailure(
await fail(
config,
ConfigProvider.fromStringPojo(["a", "value"]),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -600,11 +606,11 @@ describe("Config", () => {
const schema = Schema.Array(Schema.Finite)
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo(["1"]), [1])
await succeed(config, ConfigProvider.fromStringPojo(["1"]), [1])
// ensure array
await assertSuccess(config, ConfigProvider.fromStringPojo("1"), [1])
await assertSuccess(config, ConfigProvider.fromStringPojo(["1", "2"]), [1, 2])
await assertFailure(
await succeed(config, ConfigProvider.fromStringPojo("1"), [1])
await succeed(config, ConfigProvider.fromStringPojo(["1", "2"]), [1, 2])
await fail(
config,
ConfigProvider.fromStringPojo(["1", "value"]),
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "value"
@@ -618,8 +624,8 @@ describe("Config", () => {
const schema = Schema.Literals(["a", "b"])
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo("a"), "a")
await assertSuccess(config, ConfigProvider.fromStringPojo("b"), "b")
await succeed(config, ConfigProvider.fromStringPojo("a"), "a")
await succeed(config, ConfigProvider.fromStringPojo("b"), "b")
})
})
})
@@ -635,8 +641,8 @@ describe("Config", () => {
})
const config = Config.schema(schema)
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1", as: [] }), { a: "1", as: [] })
await assertSuccess(config, ConfigProvider.fromStringPojo({ a: "1", as: [{ a: "2", as: [] }] }), {
await succeed(config, ConfigProvider.fromStringPojo({ a: "1", as: [] }), { a: "1", as: [] })
await succeed(config, ConfigProvider.fromStringPojo({ a: "1", as: [{ a: "2", as: [] }] }), {
a: "1",
as: [{ a: "2", as: [] }]
})
@@ -646,7 +652,7 @@ describe("Config", () => {
const schema = Schema.Struct({ url: Schema.URL })
const config = Config.schema(schema)
await assertSuccess(
await succeed(
config,
ConfigProvider.fromStringPojo({ url: "https://example.com" }),
{ url: new URL("https://example.com") }
@@ -656,7 +662,7 @@ describe("Config", () => {
describe("constructors", () => {
it("fail", async () => {
await assertFailure(
await fail(
Config.fail(
new Schema.SchemaError(new Issue.Forbidden(Option.none(), { message: "failure message" }))
),
@@ -667,13 +673,13 @@ describe("Config", () => {
it("succeed", async () => {
const provider = ConfigProvider.fromStringPojo({})
await assertSuccess(Config.succeed(1), provider, 1)
await succeed(Config.succeed(1), provider, 1)
})
it("string", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "value" })
await assertSuccess(Config.string("a"), provider, "value")
await assertFailure(
await succeed(Config.string("a"), provider, "value")
await fail(
Config.string("b"),
provider,
`Expected string, got undefined
@@ -683,8 +689,8 @@ describe("Config", () => {
it("nonEmptyString", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "value", b: "" })
await assertSuccess(Config.nonEmptyString("a"), provider, "value")
await assertFailure(
await succeed(Config.nonEmptyString("a"), provider, "value")
await fail(
Config.nonEmptyString("b"),
provider,
`Expected a value with a length of at least 1, got ""
@@ -694,15 +700,15 @@ describe("Config", () => {
it("number", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "1", c: "c", d: "Infinity" })
await assertSuccess(Config.number("a"), provider, 1)
await assertSuccess(Config.number("d"), provider, Infinity)
await assertFailure(
await succeed(Config.number("a"), provider, 1)
await succeed(Config.number("d"), provider, Infinity)
await fail(
Config.number("b"),
provider,
`Expected string, got undefined
at ["b"]`
)
await assertFailure(
await fail(
Config.finite("c"),
provider,
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "c"
@@ -712,14 +718,14 @@ describe("Config", () => {
it("finite", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "1", b: "a", c: "Infinity" })
await assertSuccess(Config.finite("a"), provider, 1)
await assertFailure(
await succeed(Config.finite("a"), provider, 1)
await fail(
Config.finite("b"),
provider,
`Expected a string matching the regex (?:[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?|Infinity|-Infinity|NaN), got "a"
at ["b"]`
)
await assertFailure(
await fail(
Config.finite("c"),
provider,
`Expected a finite number, got Infinity
@@ -729,8 +735,8 @@ describe("Config", () => {
it("int", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "1", b: "1.2" })
await assertSuccess(Config.int("a"), provider, 1)
await assertFailure(
await succeed(Config.int("a"), provider, 1)
await fail(
Config.int("b"),
provider,
`Expected an integer, got 1.2
@@ -740,8 +746,8 @@ describe("Config", () => {
it("literal", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "L" })
await assertSuccess(Config.literal("L", "a"), provider, "L")
await assertFailure(
await succeed(Config.literal("L", "a"), provider, "L")
await fail(
Config.literal("-", "a"),
provider,
`Expected "-", got "L"
@@ -751,8 +757,8 @@ describe("Config", () => {
it("date", async () => {
const provider = ConfigProvider.fromStringPojo({ a: "2021-01-01", b: "invalid" })
await assertSuccess(Config.date("a"), provider, new Date("2021-01-01"))
await assertFailure(
await succeed(Config.date("a"), provider, new Date("2021-01-01"))
await fail(
Config.date("b"),
provider,
`Expected a valid date, got Invalid Date
@@ -775,15 +781,15 @@ describe("Config", () => {
failure: "value"
})
await assertSuccess(Config.boolean("a"), provider, true)
await assertSuccess(Config.boolean("b"), provider, false)
await assertSuccess(Config.boolean("c"), provider, true)
await assertSuccess(Config.boolean("d"), provider, false)
await assertSuccess(Config.boolean("e"), provider, true)
await assertSuccess(Config.boolean("f"), provider, false)
await assertSuccess(Config.boolean("g"), provider, true)
await assertSuccess(Config.boolean("h"), provider, false)
await assertFailure(
await succeed(Config.boolean("a"), provider, true)
await succeed(Config.boolean("b"), provider, false)
await succeed(Config.boolean("c"), provider, true)
await succeed(Config.boolean("d"), provider, false)
await succeed(Config.boolean("e"), provider, true)
await succeed(Config.boolean("f"), provider, false)
await succeed(Config.boolean("g"), provider, true)
await succeed(Config.boolean("h"), provider, false)
await fail(
Config.boolean("failure"),
provider,
`Expected "true" | "yes" | "on" | "1" | "false" | "no" | "off" | "0", got "value"
@@ -798,9 +804,9 @@ describe("Config", () => {
failure: "value"
})
await assertSuccess(Config.duration("a"), provider, Duration.millis(1000))
await assertSuccess(Config.duration("b"), provider, Duration.seconds(1))
await assertFailure(
await succeed(Config.duration("a"), provider, Duration.millis(1000))
await succeed(Config.duration("b"), provider, Duration.seconds(1))
await fail(
Config.duration("failure"),
provider,
`Invalid data "value"
@@ -814,8 +820,8 @@ describe("Config", () => {
failure: "-1"
})
await assertSuccess(Config.port("a"), provider, 8080)
await assertFailure(
await succeed(Config.port("a"), provider, 8080)
await fail(
Config.port("failure"),
provider,
`Expected a value between 1 and 65535, got -1
@@ -830,14 +836,14 @@ describe("Config", () => {
failure_2: "value"
})
await assertSuccess(Config.logLevel("a"), provider, "Info")
await assertFailure(
await succeed(Config.logLevel("a"), provider, "Info")
await fail(
Config.logLevel("failure_1"),
provider,
`Expected "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None", got "info"
at ["failure_1"]`
)
await assertFailure(
await fail(
Config.logLevel("failure_2"),
provider,
`Expected "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None", got "value"
@@ -850,8 +856,8 @@ describe("Config", () => {
a: "value"
})
await assertSuccess(Config.redacted("a"), provider, Redacted.make("value"))
await assertFailure(
await succeed(Config.redacted("a"), provider, Redacted.make("value"))
await fail(
Config.redacted("failure"),
provider,
`Expected string, got undefined
@@ -864,8 +870,8 @@ describe("Config", () => {
a: "https://example.com"
})
await assertSuccess(Config.url("a"), provider, new URL("https://example.com"))
await assertFailure(
await succeed(Config.url("a"), provider, new URL("https://example.com"))
await fail(
Config.url("failure"),
provider,
`Expected string, got undefined
@@ -878,7 +884,7 @@ describe("Config", () => {
const schema = Config.Record(Schema.String, Schema.String)
const config = Config.schema(schema, "OTEL_RESOURCE_ATTRIBUTES")
await assertSuccess(
await succeed(
config,
ConfigProvider.fromStringPojo({
OTEL_RESOURCE_ATTRIBUTES: {
@@ -899,7 +905,7 @@ describe("Config", () => {
const schema = Config.Record(Schema.String, Schema.String)
const config = Config.schema(schema, "OTEL_RESOURCE_ATTRIBUTES")
await assertSuccess(
await succeed(
config,
ConfigProvider.fromEnv({
env: {
@@ -918,7 +924,7 @@ describe("Config", () => {
const schema = Config.Record(Schema.String, Schema.String, { separator: "&", keyValueSeparator: "==" })
const config = Config.schema(schema, "OTEL_RESOURCE_ATTRIBUTES")
await assertSuccess(
await succeed(
config,
ConfigProvider.fromEnv({
env: {
+1 -1
View File
@@ -1,7 +1,7 @@
import { Number } from "effect"
import { Option } from "effect/data"
import { deepStrictEqual } from "node:assert"
import { describe, it } from "vitest"
import { deepStrictEqual } from "../utils/assert.ts"
describe("Option", () => {
it("getReducer", () => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { Ordering } from "effect/data"
import { deepStrictEqual } from "node:assert"
import { describe, it } from "vitest"
import { deepStrictEqual } from "../utils/assert.ts"
describe("Ordering", () => {
it("Reducer", () => {
+21 -13
View File
@@ -1,9 +1,11 @@
import { Number, pipe, String, String as Str } from "effect"
import { Equivalence, Struct, UndefinedOr } from "effect/data"
import { Schema } from "effect/schema"
import { TestSchema } from "effect/testing"
import { describe, it } from "vitest"
import { assertFalse, assertTrue, deepStrictEqual, strictEqual } from "../utils/assert.ts"
import { assertions } from "../utils/schema.ts"
const equals = TestSchema.Asserts.ast.fields.equals
describe("Struct", () => {
it("get", () => {
@@ -84,42 +86,48 @@ describe("Struct", () => {
})
it("map", () => {
assertions.schema.fields.equals(pipe({ a: Schema.String, b: Schema.Number }, Struct.map(Schema.NullOr)), {
equals(pipe({ a: Schema.String, b: Schema.Number }, Struct.map(Schema.NullOr)), {
a: Schema.NullOr(Schema.String),
b: Schema.NullOr(Schema.Number)
})
assertions.schema.fields.equals(Struct.map({ a: Schema.String, b: Schema.Number }, Schema.NullOr), {
equals(Struct.map({ a: Schema.String, b: Schema.Number }, Schema.NullOr), {
a: Schema.NullOr(Schema.String),
b: Schema.NullOr(Schema.Number)
})
})
it("mapPick", () => {
assertions.schema.fields.equals(
equals(
pipe({ a: Schema.String, b: Schema.Number }, Struct.mapPick(["a"], Schema.NullOr)),
{
a: Schema.NullOr(Schema.String),
b: Schema.Number
}
)
assertions.schema.fields.equals(Struct.mapPick({ a: Schema.String, b: Schema.Number }, ["a"], Schema.NullOr), {
a: Schema.NullOr(Schema.String),
b: Schema.Number
})
equals(
Struct.mapPick({ a: Schema.String, b: Schema.Number }, ["a"], Schema.NullOr),
{
a: Schema.NullOr(Schema.String),
b: Schema.Number
}
)
})
it("mapOmit", () => {
assertions.schema.fields.equals(
equals(
pipe({ a: Schema.String, b: Schema.Number }, Struct.mapOmit(["b"], Schema.NullOr)),
{
a: Schema.NullOr(Schema.String),
b: Schema.Number
}
)
assertions.schema.fields.equals(Struct.mapOmit({ a: Schema.String, b: Schema.Number }, ["b"], Schema.NullOr), {
a: Schema.NullOr(Schema.String),
b: Schema.Number
})
equals(
Struct.mapOmit({ a: Schema.String, b: Schema.Number }, ["b"], Schema.NullOr),
{
a: Schema.NullOr(Schema.String),
b: Schema.Number
}
)
})
it("getEquivalence", () => {
+8 -8
View File
@@ -1,9 +1,9 @@
import { Number, pipe, String } from "effect"
import { Tuple } from "effect/data"
import { Schema } from "effect/schema"
import { TestSchema } from "effect/testing"
import { deepStrictEqual, strictEqual } from "node:assert"
import { describe, it } from "vitest"
import { deepStrictEqual, strictEqual } from "../utils/assert.ts"
import { assertions } from "../utils/schema.ts"
const tuple = ["a", 2, true] as [string, number, boolean]
@@ -69,12 +69,12 @@ describe("Tuple", () => {
it("map", () => {
const tuple = [Schema.String, Schema.Number, Schema.Boolean] as const
assertions.schema.elements.equals(pipe(tuple, Tuple.map(Schema.NullOr)), [
TestSchema.Asserts.ast.elements.equals(pipe(tuple, Tuple.map(Schema.NullOr)), [
Schema.NullOr(Schema.String),
Schema.NullOr(Schema.Number),
Schema.NullOr(Schema.Boolean)
])
assertions.schema.elements.equals(Tuple.map(tuple, Schema.NullOr), [
TestSchema.Asserts.ast.elements.equals(Tuple.map(tuple, Schema.NullOr), [
Schema.NullOr(Schema.String),
Schema.NullOr(Schema.Number),
Schema.NullOr(Schema.Boolean)
@@ -83,12 +83,12 @@ describe("Tuple", () => {
it("mapPick", () => {
const tuple = [Schema.String, Schema.Number, Schema.Boolean] as const
assertions.schema.elements.equals(pipe(tuple, Tuple.mapPick([0, 2], Schema.NullOr)), [
TestSchema.Asserts.ast.elements.equals(pipe(tuple, Tuple.mapPick([0, 2], Schema.NullOr)), [
Schema.NullOr(Schema.String),
Schema.Number,
Schema.NullOr(Schema.Boolean)
])
assertions.schema.elements.equals(Tuple.mapPick(tuple, [0, 2], Schema.NullOr), [
TestSchema.Asserts.ast.elements.equals(Tuple.mapPick(tuple, [0, 2], Schema.NullOr), [
Schema.NullOr(Schema.String),
Schema.Number,
Schema.NullOr(Schema.Boolean)
@@ -97,12 +97,12 @@ describe("Tuple", () => {
it("mapOmit", () => {
const tuple = [Schema.String, Schema.Number, Schema.Boolean] as const
assertions.schema.elements.equals(pipe(tuple, Tuple.mapOmit([1], Schema.NullOr)), [
TestSchema.Asserts.ast.elements.equals(pipe(tuple, Tuple.mapOmit([1], Schema.NullOr)), [
Schema.NullOr(Schema.String),
Schema.Number,
Schema.NullOr(Schema.Boolean)
])
assertions.schema.elements.equals(Tuple.mapOmit(tuple, [1], Schema.NullOr), [
TestSchema.Asserts.ast.elements.equals(Tuple.mapOmit(tuple, [1], Schema.NullOr), [
Schema.NullOr(Schema.String),
Schema.Number,
Schema.NullOr(Schema.Boolean)
+21 -1
View File
@@ -1,7 +1,10 @@
import { Check } from "effect/schema"
import { Check, Schema } from "effect/schema"
import { TestSchema } from "effect/testing"
import { describe, it } from "vitest"
import { assertGetter, strictEqual } from "../utils/assert.ts"
const verifyGeneration = true
describe("Check", () => {
describe("Filter", () => {
describe("annotate", () => {
@@ -100,4 +103,21 @@ describe("Check", () => {
})
})
})
it("ulid", async () => {
const schema = Schema.String.check(Check.ulid())
const asserts = new TestSchema.Asserts(schema)
if (verifyGeneration) {
const arbitrary = asserts.arbitrary()
arbitrary.verifyGeneration()
}
const decoding = asserts.decoding()
await decoding.succeed("01H4PGGGJVN2DKP2K1H7EH996V")
await decoding.fail(
"",
`Expected a string matching the regex ^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$, got ""`
)
})
})
@@ -1,8 +1,9 @@
import { Effect } from "effect"
import { Result } from "effect/data"
import type { AST } from "effect/schema"
import { Schema, ToParser } from "effect/schema"
import * as assert from "node:assert"
import { describe, it } from "vitest"
import { assertions } from "../utils/schema.ts"
const assertStandardIssue = async <T, E>(
schema: Schema.Codec<T, E>,
@@ -18,7 +19,7 @@ const assertStandardIssue = async <T, E>(
Effect.runPromise
)
return assertions.result.fail(r, expected)
assert.deepStrictEqual(r, Result.fail(expected))
}
describe("makeDefault", () => {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,9 +1,98 @@
import { assertTrue, deepStrictEqual, strictEqual } from "@effect/vitest/utils"
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Effect, ServiceMap } from "effect"
import { Option } from "effect/data"
import { Option, Predicate } from "effect/data"
import { Check, Getter, Issue, Schema } from "effect/schema"
import { describe, it } from "vitest"
import { standard } from "../utils/schema.ts"
function validate<I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown
): StandardSchemaV1.Result<A> | Promise<StandardSchemaV1.Result<A>> {
return schema["~standard"].validate(input)
}
const isPromise = (value: unknown): value is Promise<unknown> => value instanceof Promise
const expectSuccess = <A>(
result: StandardSchemaV1.Result<A>,
a: A
) => {
deepStrictEqual(result, { value: a })
}
const expectSyncSuccess = <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
a: A
) => {
const result = validate(schema, input)
if (isPromise(result)) {
throw new Error("Expected value, got promise")
} else {
expectSuccess(result, a)
}
}
const expectFailure = <A>(
result: StandardSchemaV1.Result<A>,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
if (result.issues !== undefined) {
if (Predicate.isFunction(issues)) {
issues(result.issues)
} else {
deepStrictEqual(
result.issues.map((issue) => ({
message: issue.message,
path: issue.path
})),
issues
)
}
} else {
throw new Error("Expected issues, got undefined")
}
}
const expectAsyncSuccess = async <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
a: A
) => {
const result = validate(schema, input)
if (isPromise(result)) {
expectSuccess(await result, a)
} else {
throw new Error("Expected promise, got value")
}
}
const expectSyncFailure = <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
const result = validate(schema, input)
if (isPromise(result)) {
throw new Error("Expected value, got promise")
} else {
expectFailure(result, issues)
}
}
const expectAsyncFailure = async <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
const result = validate(schema, input)
if (isPromise(result)) {
expectFailure(await result, issues)
} else {
throw new Error("Expected promise, got value")
}
}
const AsyncString = Schema.String.pipe(Schema.decode({
decode: new Getter.Getter((os: Option.Option<string>) =>
@@ -27,14 +116,14 @@ describe("asStandardSchemaV1", () => {
it("sync decoding", () => {
const schema = Schema.NonEmptyString
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncSuccess(standardSchema, "a", "a")
standard.expectSyncFailure(standardSchema, null, [
expectSyncSuccess(standardSchema, "a", "a")
expectSyncFailure(standardSchema, null, [
{
message: "Expected string, got null",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: `Expected a value with a length of at least 1, got ""`,
path: []
@@ -45,14 +134,14 @@ describe("asStandardSchemaV1", () => {
it("async decoding", async () => {
const schema = AsyncNonEmptyString
const standardSchema = Schema.asStandardSchemaV1(schema)
await standard.expectAsyncSuccess(standardSchema, "a", "a")
standard.expectSyncFailure(standardSchema, null, [
await expectAsyncSuccess(standardSchema, "a", "a")
expectSyncFailure(standardSchema, null, [
{
message: "Expected string, got null",
path: []
}
])
await standard.expectAsyncFailure(standardSchema, "", [
await expectAsyncFailure(standardSchema, "", [
{
message: `Expected a value with a length of at least 1, got ""`,
path: []
@@ -75,8 +164,8 @@ describe("asStandardSchemaV1", () => {
}))
const schema = DepString
const standardSchema = Schema.asStandardSchemaV1(schema as any)
standard.expectSyncFailure(standardSchema, 1, (issues) => {
const standardSchema = Schema.asStandardSchemaV1(schema)
expectSyncFailure(standardSchema, 1, (issues) => {
strictEqual(issues.length, 1)
deepStrictEqual(issues[0].path, undefined)
assertTrue(issues[0].message.includes("Service not found: MagicNumber"))
@@ -96,8 +185,8 @@ describe("asStandardSchemaV1", () => {
}))
const schema = DepString
const standardSchema = Schema.asStandardSchemaV1(schema as any)
standard.expectSyncFailure(standardSchema, 1, (issues) => {
const standardSchema = Schema.asStandardSchemaV1(schema)
expectSyncFailure(standardSchema, 1, (issues) => {
strictEqual(issues.length, 1)
deepStrictEqual(issues[0].path, undefined)
assertTrue(issues[0].message.includes("Service not found: MagicNumber"))
@@ -111,26 +200,26 @@ describe("asStandardSchemaV1", () => {
b: Schema.NonEmptyString
})
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncSuccess(standardSchema, { a: "a", b: "b" }, { a: "a", b: "b" })
standard.expectSyncFailure(standardSchema, null, [
expectSyncSuccess(standardSchema, { a: "a", b: "b" }, { a: "a", b: "b" })
expectSyncFailure(standardSchema, null, [
{
message: "Expected object, got null",
path: []
}
])
standard.expectSyncFailure(standardSchema, { a: "a", b: "" }, [
expectSyncFailure(standardSchema, { a: "a", b: "" }, [
{
message: `Expected a value with a length of at least 1, got ""`,
path: ["b"]
}
])
standard.expectSyncFailure(standardSchema, { a: "", b: "b" }, [
expectSyncFailure(standardSchema, { a: "", b: "b" }, [
{
message: `Expected a value with a length of at least 1, got ""`,
path: ["a"]
}
])
standard.expectSyncFailure(standardSchema, { a: "", b: "" }, [
expectSyncFailure(standardSchema, { a: "", b: "" }, [
{
message: `Expected a value with a length of at least 1, got ""`,
path: ["a"]
@@ -148,7 +237,7 @@ describe("asStandardSchemaV1", () => {
b: Schema.NonEmptyString
})
const standardSchema = Schema.asStandardSchemaV1(schema, { parseOptions: { errors: "first" } })
standard.expectSyncFailure(standardSchema, { a: "", b: "" }, [
expectSyncFailure(standardSchema, { a: "", b: "" }, [
{
message: `Expected a value with a length of at least 1, got ""`,
path: ["a"]
@@ -163,7 +252,7 @@ describe("asStandardSchemaV1", () => {
})
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, { tags: ["a", ""] }, [
expectSyncFailure(standardSchema, { tags: ["a", ""] }, [
{
"message": `Expected a value with a length of at least 1, got ""`,
"path": ["tags", 1]
@@ -181,7 +270,7 @@ describe("asStandardSchemaV1", () => {
it("String & annotation", () => {
const schema = Schema.String.annotate({ message: "Custom message" })
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
@@ -192,7 +281,7 @@ describe("asStandardSchemaV1", () => {
it("String & annotation & minLength", () => {
const schema = Schema.String.annotate({ message: "Custom message" }).check(Check.nonEmpty())
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
@@ -203,13 +292,13 @@ describe("asStandardSchemaV1", () => {
it("String & minLength & annotation", () => {
const schema = Schema.String.check(Check.nonEmpty()).annotate({ message: "Custom message" })
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Expected string, got null",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: "Custom message",
path: []
@@ -220,13 +309,13 @@ describe("asStandardSchemaV1", () => {
it("String & minLength(annotation)", () => {
const schema = Schema.String.check(Check.nonEmpty({ message: "Custom message" }))
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Expected string, got null",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: "Custom message",
path: []
@@ -239,13 +328,13 @@ describe("asStandardSchemaV1", () => {
message: "Custom message 2"
})
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: "Custom message 2",
path: []
@@ -258,13 +347,13 @@ describe("asStandardSchemaV1", () => {
message: "Custom message 2"
}))
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: "Custom message 2",
path: []
@@ -277,19 +366,19 @@ describe("asStandardSchemaV1", () => {
message: "Custom message 2"
})).check(Check.maxLength(2, { message: "Custom message 3" }))
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
}
])
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: "Custom message 2",
path: []
}
])
standard.expectSyncFailure(standardSchema, "abc", [
expectSyncFailure(standardSchema, "abc", [
{
message: "Custom message 3",
path: []
@@ -304,7 +393,7 @@ describe("asStandardSchemaV1", () => {
a: Schema.String.annotateKey({ messageMissingKey: "Custom message" })
})
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, {}, [
expectSyncFailure(standardSchema, {}, [
{
message: "Custom message",
path: ["a"]
@@ -319,7 +408,7 @@ describe("asStandardSchemaV1", () => {
const standardSchema = Schema.asStandardSchemaV1(schema, {
parseOptions: { onExcessProperty: "error" }
})
standard.expectSyncFailure(standardSchema, { a: "a", b: "b" }, [
expectSyncFailure(standardSchema, { a: "a", b: "b" }, [
{
message: "Custom message",
path: ["b"]
@@ -332,13 +421,13 @@ describe("asStandardSchemaV1", () => {
it("Literals", () => {
const schema = Schema.Literals(["a", "b"]).annotate({ message: "Custom message" })
const standardSchema = Schema.asStandardSchemaV1(schema)
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Custom message",
path: []
}
])
standard.expectSyncFailure(standardSchema, "-", [
expectSyncFailure(standardSchema, "-", [
{
message: "Custom message",
path: []
@@ -354,7 +443,7 @@ describe("asStandardSchemaV1", () => {
const standardSchema = Schema.asStandardSchemaV1(schema, {
leafHook: Issue.defaultLeafHook
})
standard.expectSyncFailure(standardSchema, null, [
expectSyncFailure(standardSchema, null, [
{
message: "Expected string, got null",
path: []
@@ -367,7 +456,7 @@ describe("asStandardSchemaV1", () => {
const standardSchema = Schema.asStandardSchemaV1(schema, {
leafHook: Issue.defaultLeafHook
})
standard.expectSyncFailure(standardSchema, "", [
expectSyncFailure(standardSchema, "", [
{
message: `Expected a value with a length of at least 1, got ""`,
path: []
+107 -102
View File
@@ -1,7 +1,7 @@
import { AST, Check, Schema, ToArbitrary, ToEquivalence } from "effect/schema"
import { TestSchema } from "effect/testing"
import { deepStrictEqual } from "node:assert"
import { describe, it } from "vitest"
import { deepStrictEqual } from "../utils/assert.ts"
import { assertions } from "../utils/schema.ts"
function assertFragments(schema: Schema.Schema<any>, ctx: ToArbitrary.Context) {
const ast = schema.ast
@@ -10,114 +10,119 @@ function assertFragments(schema: Schema.Schema<any>, ctx: ToArbitrary.Context) {
deepStrictEqual(f({}), ctx)
}
function verifyGeneration<S extends Schema.Codec<unknown, unknown, never, unknown>>(schema: S) {
const asserts = new TestSchema.Asserts(schema)
asserts.arbitrary().verifyGeneration()
}
describe("ToArbitrary", () => {
it("Any", () => {
assertions.arbitrary.satisfy(Schema.Any)
verifyGeneration(Schema.Any)
})
it("Unknown", () => {
assertions.arbitrary.satisfy(Schema.Unknown)
verifyGeneration(Schema.Unknown)
})
it("Void", () => {
assertions.arbitrary.satisfy(Schema.Void)
verifyGeneration(Schema.Void)
})
it("Null", () => {
assertions.arbitrary.satisfy(Schema.Null)
verifyGeneration(Schema.Null)
})
it("String", () => {
assertions.arbitrary.satisfy(Schema.String)
verifyGeneration(Schema.String)
})
it("Number", () => {
assertions.arbitrary.satisfy(Schema.Number)
verifyGeneration(Schema.Number)
})
it("Boolean", () => {
assertions.arbitrary.satisfy(Schema.Boolean)
verifyGeneration(Schema.Boolean)
})
it("BigInt", () => {
assertions.arbitrary.satisfy(Schema.BigInt)
verifyGeneration(Schema.BigInt)
})
it("Symbol", () => {
assertions.arbitrary.satisfy(Schema.Symbol)
verifyGeneration(Schema.Symbol)
})
it("UniqueSymbol", () => {
assertions.arbitrary.satisfy(Schema.UniqueSymbol(Symbol.for("a")))
verifyGeneration(Schema.UniqueSymbol(Symbol.for("a")))
})
it("Object", () => {
assertions.arbitrary.satisfy(Schema.Object)
verifyGeneration(Schema.Object)
})
describe("Literal", () => {
it("string", () => {
assertions.arbitrary.satisfy(Schema.Literal("a"))
verifyGeneration(Schema.Literal("a"))
})
it("number", () => {
assertions.arbitrary.satisfy(Schema.Literal(1))
verifyGeneration(Schema.Literal(1))
})
it("boolean", () => {
assertions.arbitrary.satisfy(Schema.Literal(true))
verifyGeneration(Schema.Literal(true))
})
it("bigint", () => {
assertions.arbitrary.satisfy(Schema.Literal(1n))
verifyGeneration(Schema.Literal(1n))
})
})
it("Literals", () => {
assertions.arbitrary.satisfy(Schema.Literals(["a", "b", "c"]))
verifyGeneration(Schema.Literals(["a", "b", "c"]))
})
describe("TemplateLiteral", () => {
it("a", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a")])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("a b", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a"), Schema.Literal(" "), Schema.Literal("b")])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("a${string}", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a"), Schema.String])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("a${number}", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a"), Schema.Number])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("a", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a")])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("${string}", () => {
const schema = Schema.TemplateLiteral([Schema.String])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("a${string}b", () => {
const schema = Schema.TemplateLiteral([Schema.Literal("a"), Schema.String, Schema.Literal("b")])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html", async () => {
const EmailLocaleIDs = Schema.Literals(["welcome_email", "email_heading"])
const FooterLocaleIDs = Schema.Literals(["footer_title", "footer_sendoff"])
const schema = Schema.TemplateLiteral([Schema.Union([EmailLocaleIDs, FooterLocaleIDs]), "_id"])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("< + h + (1|2) + >", async () => {
@@ -126,7 +131,7 @@ describe("ToArbitrary", () => {
Schema.TemplateLiteral([Schema.Literal("h"), Schema.Union([Schema.Literal(1), Schema.Literal(2)])]),
Schema.Literal(">")
])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
})
@@ -136,7 +141,7 @@ describe("ToArbitrary", () => {
Apple,
Banana
}
assertions.arbitrary.satisfy(Schema.Enums(Fruits))
verifyGeneration(Schema.Enums(Fruits))
})
it("String enums", () => {
@@ -145,7 +150,7 @@ describe("ToArbitrary", () => {
Banana = "banana",
Cantaloupe = 0
}
assertions.arbitrary.satisfy(Schema.Enums(Fruits))
verifyGeneration(Schema.Enums(Fruits))
})
it("Const enums", () => {
@@ -154,46 +159,46 @@ describe("ToArbitrary", () => {
Banana: "banana",
Cantaloupe: 3
} as const
assertions.arbitrary.satisfy(Schema.Enums(Fruits))
verifyGeneration(Schema.Enums(Fruits))
})
})
it("Union", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Union([Schema.String, Schema.Number])
)
})
describe("Tuple", () => {
it("empty", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([])
)
})
it("required element", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.String])
)
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.String, Schema.Number])
)
})
it("optionalKey element", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.optionalKey(Schema.Number)])
)
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.String, Schema.optionalKey(Schema.Number)])
)
})
it("optional element", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.optional(Schema.Number)])
)
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Tuple([Schema.String, Schema.optional(Schema.Number)])
)
})
@@ -201,18 +206,18 @@ describe("ToArbitrary", () => {
describe("Array", () => {
it("Array", () => {
assertions.arbitrary.satisfy(Schema.Array(Schema.String))
verifyGeneration(Schema.Array(Schema.String))
})
})
it("TupleWithRest", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.TupleWithRest(Schema.Tuple([Schema.Boolean]), [Schema.Number, Schema.String])
)
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.TupleWithRest(Schema.Tuple([]), [Schema.Number, Schema.String])
)
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.TupleWithRest(Schema.Tuple([Schema.optionalKey(Schema.Boolean)]), [Schema.Number]).check(
Check.minLength(3)
)
@@ -221,33 +226,33 @@ describe("ToArbitrary", () => {
describe("Struct", () => {
it("empty", () => {
assertions.arbitrary.satisfy(Schema.Struct({}))
verifyGeneration(Schema.Struct({}))
})
it("required fields", () => {
assertions.arbitrary.satisfy(Schema.Struct({
verifyGeneration(Schema.Struct({
a: Schema.String
}))
assertions.arbitrary.satisfy(Schema.Struct({
verifyGeneration(Schema.Struct({
a: Schema.String,
b: Schema.Number
}))
})
it("required field with undefined", () => {
assertions.arbitrary.satisfy(Schema.Struct({
verifyGeneration(Schema.Struct({
a: Schema.UndefinedOr(Schema.String)
}))
})
it("optionalKey field", () => {
assertions.arbitrary.satisfy(Schema.Struct({
verifyGeneration(Schema.Struct({
a: Schema.optionalKey(Schema.String)
}))
})
it("optional field", () => {
assertions.arbitrary.satisfy(Schema.Struct({
verifyGeneration(Schema.Struct({
a: Schema.optional(Schema.String)
}))
})
@@ -255,20 +260,20 @@ describe("ToArbitrary", () => {
describe("Record", () => {
it("Record(String, Number)", () => {
assertions.arbitrary.satisfy(Schema.Record(Schema.String, Schema.Number))
verifyGeneration(Schema.Record(Schema.String, Schema.Number))
})
it("Record(Symbol, Number)", () => {
assertions.arbitrary.satisfy(Schema.Record(Schema.Symbol, Schema.Number))
verifyGeneration(Schema.Record(Schema.Symbol, Schema.Number))
})
})
it("StructWithRest", () => {
assertions.arbitrary.satisfy(Schema.StructWithRest(
verifyGeneration(Schema.StructWithRest(
Schema.Struct({ a: Schema.Number }),
[Schema.Record(Schema.String, Schema.Number)]
))
assertions.arbitrary.satisfy(Schema.StructWithRest(
verifyGeneration(Schema.StructWithRest(
Schema.Struct({ a: Schema.Number }),
[Schema.Record(Schema.Symbol, Schema.Number)]
))
@@ -280,7 +285,7 @@ describe("ToArbitrary", () => {
a: Schema.String
}) {}
const schema = A
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
})
@@ -291,13 +296,13 @@ describe("ToArbitrary", () => {
Schema.Number,
Schema.NullOr(Rec)
])
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("Array", () => {
const Rec = Schema.suspend((): Schema.Codec<any> => schema)
const schema: any = Schema.Array(Schema.Union([Schema.String, Rec]))
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("Struct", () => {
@@ -306,13 +311,13 @@ describe("ToArbitrary", () => {
a: Schema.String,
as: Schema.Array(Rec)
})
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("Record", () => {
const Rec = Schema.suspend((): Schema.Codec<any> => schema)
const schema = Schema.Record(Schema.String, Rec)
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("optional", () => {
@@ -320,7 +325,7 @@ describe("ToArbitrary", () => {
const schema: any = Schema.Struct({
a: Schema.optional(Rec)
})
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("Array + Array", () => {
@@ -329,7 +334,7 @@ describe("ToArbitrary", () => {
a: Schema.Array(Rec),
b: Schema.Array(Rec)
})
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("optional + Array", () => {
@@ -338,7 +343,7 @@ describe("ToArbitrary", () => {
a: Schema.optional(Rec),
b: Schema.Array(Rec)
})
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it.skip("mutually suspended schemas", { retry: 5 }, () => {
@@ -365,7 +370,7 @@ describe("ToArbitrary", () => {
left: Expression,
right: Expression
})
assertions.arbitrary.satisfy(Operation)
verifyGeneration(Operation)
})
it("Option", () => {
@@ -374,173 +379,173 @@ describe("ToArbitrary", () => {
a: Schema.String,
as: Schema.Option(Rec)
})
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("Map", () => {
const Rec = Schema.suspend((): Schema.Codec<any> => schema)
const schema = Schema.Map(Schema.String, Rec)
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
})
describe("checks", () => {
it("minLength(2)", () => {
assertions.arbitrary.satisfy(Schema.String.pipe(Schema.check(Check.minLength(2))))
assertions.arbitrary.satisfy(Schema.Array(Schema.String).pipe(Schema.check(Check.minLength(2))))
verifyGeneration(Schema.String.pipe(Schema.check(Check.minLength(2))))
verifyGeneration(Schema.Array(Schema.String).pipe(Schema.check(Check.minLength(2))))
})
it("maxLength(2)", () => {
assertions.arbitrary.satisfy(Schema.String.pipe(Schema.check(Check.maxLength(2))))
assertions.arbitrary.satisfy(Schema.Array(Schema.String).pipe(Schema.check(Check.maxLength(2))))
verifyGeneration(Schema.String.pipe(Schema.check(Check.maxLength(2))))
verifyGeneration(Schema.Array(Schema.String).pipe(Schema.check(Check.maxLength(2))))
})
it("minLength(2) & maxLength(4)", () => {
assertions.arbitrary.satisfy(Schema.String.pipe(Schema.check(Check.minLength(2), Check.maxLength(4))))
assertions.arbitrary.satisfy(
verifyGeneration(Schema.String.pipe(Schema.check(Check.minLength(2), Check.maxLength(4))))
verifyGeneration(
Schema.Array(Schema.String).pipe(Schema.check(Check.minLength(2), Check.maxLength(4)))
)
})
it("length(2)", () => {
assertions.arbitrary.satisfy(Schema.String.pipe(Schema.check(Check.length(2))))
assertions.arbitrary.satisfy(Schema.Array(Schema.String).pipe(Schema.check(Check.length(2))))
verifyGeneration(Schema.String.pipe(Schema.check(Check.length(2))))
verifyGeneration(Schema.Array(Schema.String).pipe(Schema.check(Check.length(2))))
})
it("minEntries(2)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Record(Schema.String, Schema.Number).check(Check.minEntries(2))
)
})
it("maxEntries(2)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Record(Schema.String, Schema.Number).check(Check.maxEntries(2))
)
})
it("minEntries(2) & maxEntries(4)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Record(Schema.String, Schema.Number).check(Check.minEntries(2), Check.maxEntries(4))
)
})
it("entries(2)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Record(Schema.String, Schema.Number).check(Check.entries(2))
)
})
it("int", () => {
const schema = Schema.Number.check(Check.int())
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("int32", () => {
const schema = Schema.Number.check(Check.int32())
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("regex", () => {
assertions.arbitrary.satisfy(Schema.String.check(Check.regex(/^[A-Z]{3}[0-9]{3}$/)))
verifyGeneration(Schema.String.check(Check.regex(/^[A-Z]{3}[0-9]{3}$/)))
})
it("nonEmpty + regex", () => {
assertions.arbitrary.satisfy(Schema.NonEmptyString.check(Check.regex(/^[-]*$/)))
verifyGeneration(Schema.NonEmptyString.check(Check.regex(/^[-]*$/)))
})
it("regex + regex", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.String.check(Check.regex(/^[^A-Z]*$/), Check.regex(/^0x[0-9a-f]{40}$/))
)
})
it("greaterThanOrEqualToDate", () => {
assertions.arbitrary.satisfy(Schema.Date.check(Check.greaterThanOrEqualToDate(new Date(0))))
verifyGeneration(Schema.Date.check(Check.greaterThanOrEqualToDate(new Date(0))))
})
it("lessThanOrEqualToDate", () => {
assertions.arbitrary.satisfy(Schema.Date.check(Check.lessThanOrEqualToDate(new Date(10))))
verifyGeneration(Schema.Date.check(Check.lessThanOrEqualToDate(new Date(10))))
})
it("betweenDate", () => {
assertions.arbitrary.satisfy(Schema.Date.check(Check.betweenDate(new Date(0), new Date(10))))
verifyGeneration(Schema.Date.check(Check.betweenDate(new Date(0), new Date(10))))
})
it("ValidDate", () => {
assertions.arbitrary.satisfy(Schema.ValidDate)
verifyGeneration(Schema.ValidDate)
})
it("greaterThanOrEqualToBigInt", () => {
assertions.arbitrary.satisfy(Schema.BigInt.check(Check.greaterThanOrEqualToBigInt(BigInt(0))))
verifyGeneration(Schema.BigInt.check(Check.greaterThanOrEqualToBigInt(BigInt(0))))
})
it("lessThanOrEqualToBigInt", () => {
assertions.arbitrary.satisfy(Schema.BigInt.check(Check.lessThanOrEqualToBigInt(BigInt(10))))
verifyGeneration(Schema.BigInt.check(Check.lessThanOrEqualToBigInt(BigInt(10))))
})
it("betweenBigInt", () => {
assertions.arbitrary.satisfy(Schema.BigInt.check(Check.betweenBigInt(BigInt(0), BigInt(10))))
verifyGeneration(Schema.BigInt.check(Check.betweenBigInt(BigInt(0), BigInt(10))))
})
})
it("Finite", () => {
assertions.arbitrary.satisfy(Schema.Finite)
verifyGeneration(Schema.Finite)
})
it("Date", () => {
assertions.arbitrary.satisfy(Schema.Date)
verifyGeneration(Schema.Date)
})
it("URL", () => {
assertions.arbitrary.satisfy(Schema.URL)
verifyGeneration(Schema.URL)
})
it("Duration", () => {
assertions.arbitrary.satisfy(Schema.Duration)
verifyGeneration(Schema.Duration)
})
it("DateTimeUtc", () => {
assertions.arbitrary.satisfy(Schema.DateTimeUtc)
verifyGeneration(Schema.DateTimeUtc)
})
it("UnknownFromJsonString", () => {
assertions.arbitrary.satisfy(Schema.UnknownFromJsonString)
verifyGeneration(Schema.UnknownFromJsonString)
})
it("Option(String)", () => {
assertions.arbitrary.satisfy(Schema.Option(Schema.String))
verifyGeneration(Schema.Option(Schema.String))
})
it("Result(Number, String)", () => {
assertions.arbitrary.satisfy(Schema.Result(Schema.Number, Schema.String))
verifyGeneration(Schema.Result(Schema.Number, Schema.String))
})
describe("Map", () => {
it("Map(String, Number)", () => {
assertions.arbitrary.satisfy(Schema.Map(Schema.String, Schema.Number))
verifyGeneration(Schema.Map(Schema.String, Schema.Number))
})
it("minSize(2)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Map(Schema.String, Schema.Number).check(Check.minSize(2))
)
})
it("maxSize(4)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Map(Schema.String, Schema.Number).check(Check.maxSize(4))
)
})
it("minSize(2) & maxSize(4)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Map(Schema.String, Schema.Number).check(Check.minSize(2), Check.maxSize(4))
)
})
it("size(2)", () => {
assertions.arbitrary.satisfy(
verifyGeneration(
Schema.Map(Schema.String, Schema.Number).check(Check.size(2))
)
})
@@ -549,12 +554,12 @@ describe("ToArbitrary", () => {
describe("Redacted", () => {
it("Redacted(String)", () => {
const schema = Schema.Redacted(Schema.String)
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
it("with label", () => {
const schema = Schema.Redacted(Schema.String, { label: "password" })
assertions.arbitrary.satisfy(schema)
verifyGeneration(schema)
})
})
@@ -0,0 +1,88 @@
import { Effect, ServiceMap } from "effect"
import { Option } from "effect/data"
import { Check, Getter, Issue, Schema } from "effect/schema"
import { TestSchema } from "effect/testing"
import { describe, it } from "vitest"
describe("TestSchema", () => {
it("decoding", async () => {
const schema = Schema.FiniteFromString.check(Check.positive())
const assert = new TestSchema.Asserts(schema)
const decoding = assert.decoding()
await decoding.succeed("1", 1)
await decoding.fail("-1", `Expected a value greater than 0, got -1`)
await decoding.fail("a", `Expected a finite number, got NaN`)
})
it("decoding.provide", async () => {
class Service extends ServiceMap.Key<Service, { fallback: Effect.Effect<string> }>()("Service") {}
const schema = Schema.String.pipe(
Schema.decode({
decode: Getter.checkEffect((s) =>
Effect.gen(function*() {
yield* Service
if (s.length === 0) {
return new Issue.InvalidValue(Option.some(s), { message: "input should not be empty string" })
}
})
),
encode: Getter.passthrough()
})
)
const asserts = new TestSchema.Asserts(schema)
const decoding = asserts.decoding().provide(
Service,
{ fallback: Effect.succeed("b") }
)
await decoding.succeed("a")
await decoding.fail(
"",
"input should not be empty string"
)
})
it("encoding", async () => {
const schema = Schema.FiniteFromString.check(Check.positive())
const assert = new TestSchema.Asserts(schema)
const encoding = assert.encoding()
await encoding.succeed(1, "1")
await encoding.fail(-1, `Expected a value greater than 0, got -1`)
})
it("encoding.provide", async () => {
class Service extends ServiceMap.Key<Service, { fallback: Effect.Effect<string> }>()("Service") {}
const schema = Schema.String.pipe(
Schema.decode({
decode: Getter.passthrough(),
encode: Getter.checkEffect((s) =>
Effect.gen(function*() {
yield* Service
if (s.length === 0) {
return new Issue.InvalidValue(Option.some(s), { message: "input should not be empty string" })
}
})
)
})
)
const asserts = new TestSchema.Asserts(schema)
const encoding = asserts.encoding().provide(
Service,
{ fallback: Effect.succeed("b") }
)
await encoding.succeed("a")
await encoding.fail(
"",
"input should not be empty string"
)
})
it("verifyLosslessTransformation", async () => {
const schema = Schema.FiniteFromString.check(Check.positive())
const assert = new TestSchema.Asserts(schema)
await assert.verifyLosslessTransformation()
})
})
@@ -1,8 +1,8 @@
import { describe, it } from "@effect/vitest"
import { ToOptic } from "effect/schema"
import { Schema, Serializer, ToOptic } from "effect/schema"
import { TestSchema } from "effect/testing"
import { Cookies } from "effect/unstable/http"
import { assertSuccess } from "../../utils/assert.ts"
import { assertions } from "../../utils/schema.ts"
describe("Cookies", () => {
describe("CookiesSchema", () => {
@@ -21,8 +21,11 @@ describe("Cookies", () => {
it("defaultJsonSerializer", async () => {
const schema = Cookies.CookiesSchema
await assertions.serialization.json.typeCodec.succeed(
schema,
const asserts = new TestSchema.Asserts(Serializer.json(Schema.typeCodec(schema)))
const encoding = asserts.encoding()
await encoding.succeed(
Cookies.fromSetCookie([
"sessionId=abc123; Path=/; HttpOnly; Secure",
"theme=dark; Path=/; Max-Age=3600",
@@ -1,7 +1,7 @@
import { describe, it } from "@effect/vitest"
import { ToJsonSchema } from "effect/schema"
import { Multipart } from "effect/unstable/http"
import { deepStrictEqual } from "../../utils/assert.ts"
import { deepStrictEqual } from "node:assert"
describe("Multipart", () => {
describe("FileSchema", () => {
-574
View File
@@ -1,574 +0,0 @@
import type { StandardSchemaV1 } from "@standard-schema/spec"
import { Effect } from "effect"
import type { ServiceMap } from "effect"
import { Predicate, Record, Result } from "effect/data"
import { AST, Issue, Schema, Serializer, ToArbitrary, ToParser } from "effect/schema"
import { FastCheck } from "effect/testing"
import { deepStrictEqual, fail, strictEqual, throws } from "./assert.ts"
export const assertions = make({
deepStrictEqual,
strictEqual,
throws,
fail
})
function make(asserts: {
readonly deepStrictEqual: (actual: unknown, expected: unknown) => void
readonly strictEqual: (actual: unknown, expected: unknown, message?: string) => void
readonly throws: (thunk: () => void, error?: Error | ((u: unknown) => undefined)) => void
readonly fail: (message: string) => void
}) {
const { deepStrictEqual, fail, strictEqual, throws } = asserts
function assertInstanceOf<C extends abstract new(...args: any) => any>(
value: unknown,
constructor: C,
message?: string,
..._: Array<never>
): asserts value is InstanceType<C> {
if (!(value instanceof constructor)) {
fail(message ?? `expected ${value} to be an instance of ${constructor}`)
}
}
const out = {
schema: {
fields: {
equals: (a: Schema.Struct.Fields, b: Schema.Struct.Fields) => {
deepStrictEqual(Record.map(a, AST.getAST), Record.map(b, AST.getAST))
}
},
elements: {
equals: (a: Schema.Tuple.Elements, b: Schema.Tuple.Elements) => {
deepStrictEqual(a.map(AST.getAST), b.map(AST.getAST))
}
}
},
arbitrary: {
/**
* Verifies that the schema generates valid arbitrary values that satisfy
* the schema.
*/
satisfy<T, E, RE>(schema: Schema.Codec<T, E, never, RE>, options?: {
readonly params?: FastCheck.Parameters<[T]> | undefined
}) {
const params = options?.params
const is = Schema.is(schema)
const arb = ToArbitrary.make(schema)
FastCheck.assert(FastCheck.property(arb, (a) => is(a)), { numRuns: 20, ...params })
}
},
promise: {
async succeed<A>(promise: Promise<A>, expected: A) {
deepStrictEqual(await promise, expected)
},
async fail<A>(promise: Promise<A>, message: string) {
try {
const a = await promise
throw new Error(`Promise didn't reject, got: ${a}`)
} catch (e: unknown) {
if (Issue.isIssue(e)) {
strictEqual(e.toString(), message)
} else {
throw new Error(`Unknown promise rejection: ${e}`)
}
}
}
},
ast: {
equals: <A, I, RD, RE>(a: Schema.Codec<A, I, RD, RE>, b: Schema.Codec<A, I, RD, RE>) => {
deepStrictEqual(a.ast, b.ast)
}
},
make: {
async succeed<S extends Schema.Top>(
schema: S,
input: S["~type.make.in"],
expected?: S["Type"]
) {
return out.effect.succeed(
ToParser.makeEffect(schema)(input),
expected === undefined ? input : expected
)
},
async fail<S extends Schema.Top>(
schema: S,
input: unknown,
message: string,
options?: Schema.MakeOptions
) {
return out.effect.fail(ToParser.makeEffect(schema)(input, options), message)
}
},
makeUnsafe: {
/**
* Ensures that the given constructor produces the expected value.
*/
succeed<S extends Schema.Top>(
schema: S,
input: S["~type.make.in"],
expected?: S["Type"]
) {
deepStrictEqual(schema.makeUnsafe(input), expected === undefined ? input : expected)
},
/**
* Ensures that the given constructor throws the expected error.
*/
fail<S extends Schema.Top>(
schema: S,
input: unknown,
message: string
) {
throws(() => schema.makeUnsafe(input), (err) => {
assertInstanceOf(err, Error)
strictEqual(err.message, message)
})
}
},
serialization: {
json: {
typeCodec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
expected?: unknown
) {
return out.effect.succeed(
Schema.encodeEffect(Serializer.json(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
message: string
) {
return out.effect.fail(
Schema.encodeEffect(Serializer.json(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
)
}
},
codec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
expected?: unknown
) {
return out.encoding.succeed(
Serializer.json(schema),
input,
{ expected: arguments.length > 2 ? expected : input }
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
message: string
) {
return out.encoding.fail(Serializer.json(schema), input, message)
}
}
},
stringPojo: {
typeCodec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
expected?: Serializer.StringPojo
) {
return out.effect.succeed(
Schema.encodeEffect(Serializer.stringPojo(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
message: string
) {
return out.effect.fail(
Schema.encodeEffect(Serializer.stringPojo(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
)
}
}
}
},
deserialization: {
json: {
typeCodec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
expected?: A
) {
return out.effect.succeed(
Schema.decodeEffect(Serializer.json(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
message: string
) {
return out.effect.fail(
Schema.decodeEffect(Serializer.json(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
)
}
},
codec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
expected?: A
) {
return out.decoding.succeed(
Serializer.json(schema),
input,
{ expected: arguments.length > 2 ? expected : input }
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
message: string
) {
return out.decoding.fail(Serializer.json(schema), input, message)
}
}
},
stringPojo: {
typeCodec: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: Serializer.StringPojo,
expected?: A
) {
return out.effect.succeed(
Schema.decodeEffect(Serializer.stringPojo(Schema.typeCodec(schema)))(input),
arguments.length > 2 ? expected : input
)
},
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: Serializer.StringPojo,
message: string
) {
return out.effect.fail(
Schema.decodeEffect(Serializer.stringPojo(Schema.typeCodec(schema)))(input).pipe(
Effect.mapError((err) => err.issue)
),
message
)
}
}
}
},
decoding: {
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
options?: {
readonly expected?: A
readonly parseOptions?: AST.ParseOptions | undefined
readonly provide?: ReadonlyArray<readonly [ServiceMap.Key<any, any>, any]> | undefined
} | undefined
) {
const decoded = ToParser.decodeUnknownEffect(schema)(input, options?.parseOptions)
const effWithMessage = Effect.catch(decoded, (issue) => Effect.fail(issue.toString()))
let provided = effWithMessage
if (options?.provide) {
for (const [tag, value] of options.provide) {
provided = Effect.provideService(provided, tag, value)
}
}
return out.effect.succeed(
provided,
options && Object.hasOwn(options, "expected") ? options.expected : input
)
},
/**
* Attempts to decode the given input using the provided schema. If the
* decoding fails, the error message is compared to the expected message.
* Otherwise the test fails.
*/
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
message: string,
options?: {
readonly parseOptions?: AST.ParseOptions | undefined
readonly provide?: ReadonlyArray<readonly [ServiceMap.Key<any, any>, any]> | undefined
} | undefined
) {
const decoded = ToParser.decodeUnknownEffect(schema)(input, options?.parseOptions)
let provided = decoded
if (options?.provide) {
for (const [tag, value] of options.provide) {
provided = Effect.provideService(provided, tag, value)
}
}
return out.effect.fail(provided, message)
}
},
encoding: {
/**
* Attempts to encode the given input using the provided schema. If the
* decoding is successful, the decoded value is compared to the expected
* value. Otherwise the test fails.
*/
async succeed<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: A,
options?: {
expected?: I
readonly parseOptions?: AST.ParseOptions | undefined
} | undefined
) {
// Account for `expected` being `undefined`
const encoded = ToParser.encodeUnknownEffect(schema)(input, options?.parseOptions)
return out.effect.succeed(
Effect.catch(encoded, (issue) => Effect.fail(issue.toString())),
options && Object.hasOwn(options, "expected") ? options.expected : input
)
},
/**
* Attempts to encode the given input using the provided schema. If the
* decoding fails, the error message is compared to the expected message.
* Otherwise the test fails.
*/
async fail<const A, const I, RD, RE>(
schema: Schema.Codec<A, I, RD, RE>,
input: unknown,
message: string,
options?: {
readonly parseOptions?: AST.ParseOptions | undefined
} | undefined
) {
const encoded = ToParser.encodeUnknownEffect(schema)(input, options?.parseOptions)
return out.effect.fail(encoded, message)
}
},
effect: {
/**
* Verifies that the effect succeeds with the expected value.
*/
async succeed<const A, E, R>(
effect: Effect.Effect<A, E, R>,
a: A
) {
const r = Effect.result(effect) as Effect.Effect<Result.Result<A, E>>
deepStrictEqual(await Effect.runPromise(r), Result.succeed(a))
},
/**
* Verifies that the effect fails with the expected message.
*/
async fail<A, R>(
effect: Effect.Effect<A, Issue.Issue, R>,
message: string
) {
const effectWithMessage = Effect.catch(
effect,
(issue) => Effect.fail(issue.toString())
)
const r = Effect.result(effectWithMessage) as Effect.Effect<Result.Result<A, string>>
return out.result.fail(await Effect.runPromise(r), message)
}
},
result: {
/**
* Verifies that the Result is an `Ok` with the expected value.
*/
succeed<const A, E>(result: Result.Result<A, E>, right: A) {
if (Result.isSuccess(result)) {
deepStrictEqual(result.success, right)
} else {
// eslint-disable-next-line no-console
console.log(result.failure)
fail(`expected a Success, got a Failure: ${result.failure}`)
}
},
/**
* Verifies that the Result is an `Err` with the expected value.
*/
fail<A, const E>(result: Result.Result<A, E>, err: E | ((err: E) => void)) {
if (Result.isFailure(result)) {
if (Predicate.isFunction(err)) {
err(result.failure)
} else {
deepStrictEqual(result.failure, err)
}
} else {
// eslint-disable-next-line no-console
console.log(result.success)
fail(`expected a Failure, got a Success: ${result.success}`)
}
},
/**
* Verifies that the Result is an `Err` with the expected message.
*/
async failMessage<A>(encoded: Result.Result<A, Issue.Issue>, message: string | ((message: string) => void)) {
const encodedWithMessage = Effect.gen(function*() {
if (Result.isFailure(encoded)) {
const message = encoded.failure.toString()
return yield* Effect.fail(message)
}
return encoded.success
})
const result = await Effect.runPromise(Effect.result(encodedWithMessage))
out.result.fail(result, message)
}
},
asserts: {
succeed<T, E, RE>(schema: Schema.Codec<T, E, never, RE>, input: unknown) {
deepStrictEqual(Schema.asserts(schema)(input), undefined)
},
fail<T, E, RE>(schema: Schema.Codec<T, E, never, RE>, input: unknown, message: string) {
throws(() => Schema.asserts(schema)(input), (err) => {
assertInstanceOf(err, Error)
strictEqual(err.message, message)
})
}
}
}
return out
}
function validate<I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown
): StandardSchemaV1.Result<A> | Promise<StandardSchemaV1.Result<A>> {
return schema["~standard"].validate(input)
}
const isPromise = (value: unknown): value is Promise<unknown> => value instanceof Promise
const expectSuccess = <A>(
result: StandardSchemaV1.Result<A>,
a: A
) => {
deepStrictEqual(result, { value: a })
}
const expectFailure = <A>(
result: StandardSchemaV1.Result<A>,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
if (result.issues !== undefined) {
if (Predicate.isFunction(issues)) {
issues(result.issues)
} else {
deepStrictEqual(
result.issues.map((issue) => ({
message: issue.message,
path: issue.path
})),
issues
)
}
} else {
throw new Error("Expected issues, got undefined")
}
}
const expectSyncSuccess = <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
a: A
) => {
const result = validate(schema, input)
if (isPromise(result)) {
throw new Error("Expected value, got promise")
} else {
expectSuccess(result, a)
}
}
const expectAsyncSuccess = async <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
a: A
) => {
const result = validate(schema, input)
if (isPromise(result)) {
expectSuccess(await result, a)
} else {
throw new Error("Expected promise, got value")
}
}
const expectSyncFailure = <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
const result = validate(schema, input)
if (isPromise(result)) {
throw new Error("Expected value, got promise")
} else {
expectFailure(result, issues)
}
}
const expectAsyncFailure = async <I, A>(
schema: StandardSchemaV1<I, A>,
input: unknown,
issues: ReadonlyArray<StandardSchemaV1.Issue> | ((issues: ReadonlyArray<StandardSchemaV1.Issue>) => void)
) => {
const result = validate(schema, input)
if (isPromise(result)) {
expectFailure(await result, issues)
} else {
throw new Error("Expected promise, got value")
}
}
export const standard = {
expectSyncSuccess,
expectSyncFailure,
expectAsyncSuccess,
expectAsyncFailure
}